<template>
  <el-form
    :label-position="'right'"
    label-width="120px"
    :model="systemForm"
    :rules="formRules"
    ref="systemRef"
    style="max-width: 66%">
    <el-form-item label="所属机构" prop="organization_id">
      <el-tree-select
        v-model="systemForm.organization_id"
        :data="orgData"
        :props="treeProps"
        :render-after-expand="false"
        :disabled="formType"
        style="width: 100%" />
    </el-form-item>
    <el-form-item label="业务系统编码" prop="business_code" v-if="formType">
      <el-input v-model="systemForm.business_code" :disabled="formType" />
    </el-form-item>
    <el-form-item label="业务系统名称" prop="business_name">
      <el-input v-model="systemForm.business_name" />
    </el-form-item>
    <el-form-item label="AppId" prop="appid" v-if="formType">
      <el-input v-model="systemForm.appid" :disabled="formType" style="width: 80%" />
      <span class="pl-1"><el-button type="primary" @click="copyText(systemForm.appid)">复制</el-button></span>
    </el-form-item>
    <el-form-item label="AppSecret" prop="appsecret" v-if="formType">
      <el-input v-model="systemForm.appsecret" :disabled="formType" style="width: 80%" />
      <span class="pl-1"><el-button type="primary" @click="copyText(systemForm.appsecret)">复制</el-button></span>
      <span class="pl-1"><el-button type="primary" @click="resetSecret">重置</el-button></span>
    </el-form-item>
    <el-form-item label="系统LOGO" prop="logo">
      <bg-upload-image
        v-model="systemForm.logo"
        :showTips="true"
        :limit="1"
        :fileSize="500"
        :fileSizeUnit="'KB'"
        listType="picture-card"
        :accept="['.jpg', '.jpeg', '.png']"
        customTips="请选择图片上传：大小120 * 120像素支持jpg、png等格式，图片需小于500KB"></bg-upload-image>
    </el-form-item>
    <el-form-item label="业务系统概述" prop="business_desc">
      <el-input type="textarea" :rows="3" v-model="systemForm.business_desc" show-word-limit maxlength="300" />
    </el-form-item>
    <el-form-item label="角色" prop="system_role_id" v-if="!formType">
      <el-select v-model="systemForm.system_role_id" placeholder="请选择角色" :disabled="true" style="width: 100%">
        <el-option v-for="item in roleList" :key="item.role_id" :label="item.role_name" :value="item.role_id" />
      </el-select>
    </el-form-item>
    <el-form-item label="账号" prop="system_account">
      <el-input v-model="systemForm.system_account" />
    </el-form-item>
    <el-form-item label="密码" prop="password" v-if="!formType">
      <el-input :type="password_eye ? 'text' : 'password'" v-model="systemForm.password">
        <template #suffix>
          <bg-icon @click="password_eye = !password_eye" class="icon_eye" icon="#bg-ic-eye"></bg-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item label="确认密码" prop="confirm_password" v-if="!formType">
      <el-input :type="confirm_eye ? 'text' : 'password'" v-model="systemForm.confirm_password">
        <template #suffix>
          <bg-icon @click="confirm_eye = !confirm_eye" class="icon_eye" icon="#bg-ic-eye"></bg-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item label="访问地址" prop="access_address">
      <el-input v-model="systemForm.access_address" />
    </el-form-item>
    <el-form-item label="开发厂商名称" prop="develop_id">
      <el-select v-model="systemForm.develop_id" placeholder="请选择开发厂商" style="width: 100%">
        <el-option v-for="item in firmList" :key="item.dict_id" :label="item.dict_name" :value="item.dict_id" />
      </el-select>
    </el-form-item>
    <el-form-item label="是否启用" prop="state">
      <bg-switch :labels="['否', '是']" :values="[0, 1]" v-model="systemForm.state"></bg-switch>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { reactive, ref, onBeforeMount, onMounted, computed } from "vue";
import axios from "@/request/http.js";
import { ElMessage } from "element-plus";
const props = defineProps({
  formType: {
    type: Boolean,
    default: false, //false 新增 true 编辑
  },
  id: {
    type: String,
    default: "",
  },
});
const systemForm = reactive({
  organization_id: "",
  business_code: "",
  business_name: "",
  business_desc: "",
  logo: [],
  system_role_id: "",
  system_account: "",
  password: "",
  confirm_password: "",
  access_address: "",
  develop_id: "",
  state: 1,
  appid: "",
  appsecret: "",
});
const password_eye = ref(false);
const confirm_eye = ref(false);

const validatePass = (rule, value, callback) => {
  if (value !== systemForm.password) {
    callback(new Error("密码输入不一致"));
  } else {
    callback();
  }
};
const validateBusinessName = (rule, value, callback) => {
  let reg = /^[a-zA-Z0-9\u4e00-\u9fa5]+$/;
  if (!reg.test(value)) {
    callback(new Error("只能输入字母、数字和汉字"));
  } else {
    let params = null;
    if (props.id) {
      params = { id: parseInt(props.id), business_name: value, organization_id: systemForm.organization_id };
    } else {
      params = { business_name: value, organization_id: systemForm.organization_id };
    }

    axios.post(`/apaas/system/v5/user/check/business`, params).then((res) => {
      if (res.data.code == 200) {
        callback();
      } else {
        callback(new Error(res.data.data));
      }
    });
  }
};

const validateSystemAccount = (rule, value, callback) => {
  let reg = /^[a-zA-Z0-9]+$/;
  if (!reg.test(value)) {
    callback(new Error("只能输入字母和数字"));
  } else {
    let params = null;
    if (props.id) {
      params = { id: parseInt(props.id), system_account: value };
    } else {
      params = { system_account: value };
    }

    axios.post(`/apaas/system/v5/user/check/account`, params).then((res) => {
      if (res.data.code == 200) {
        callback();
      } else {
        callback(new Error(res.data.data));
      }
    });
  }
};

const formRules = reactive({
  organization_id: [{ required: true, message: "请选择组织机构", trigger: "change" }],
  business_name: [
    { required: true, message: "请输入业务系统名称", trigger: "blur" },
    { max: 50, message: "业务系统名称最大长度为50个字符", trigger: "blur" },
    { validator: validateBusinessName, trigger: "blur" },
  ],
  system_role_id: [{ required: true, message: "请选择角色", trigger: "blur" }],
  system_account: [
    { required: true, message: "请输入账号", trigger: "blur" },
    { min: 4, message: "帐号长度不得低于4个字符", trigger: "blur" },
    { max: 20, message: "帐号最大长度为20个字符", trigger: "blur" },
    { validator: validateSystemAccount, trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 8, message: "密码长度不得低于8位", trigger: "blur" },
  ],
  confirm_password: [
    { required: true, message: "请确认密码", trigger: "blur" },
    { validator: validatePass, trigger: "blur" },
  ],
  access_address: [{ max: 500, message: "访问地址最大长度为500个字符", trigger: "blur" }],
  develop_id: [{ required: true, message: "请选择开发厂商", trigger: "change" }],
});

const systemRef = ref(null);
const emit = defineEmits(["action"]);
const roleList = ref([]);
const firmList = ref([]);

const submitForm = async () => {
  if (!systemRef) return;
  await systemRef.value.validate((valid, fields) => {
    if (valid) {
      emit("action", systemForm);
    } else {
      emit("action", null);
    }
  });
};

const clearForm = () => {
  if (!systemRef) return;
  systemRef.value.resetFields();
  systemForm.system_role_id = roleList.value[0].role_id;
};

const setForm = (data) => {
  Object.assign(systemForm, data);
};

const orgData = ref([]);
const treeProps = {
  label: "name",
  children: "Child",
  value: "organization_id",
};
const getOrgTree = () => {
  axios.get(`/apaas/system/v5/org/tree`).then((res) => {
    if (res.data.code == 200) {
      const orgDataTemp = res.data.data || [];
      orgDataTemp.shift();
      orgData.value = orgDataTemp;
    } else {
      ElMessage.error(res.data.data);
    }
  });
};

const copyText = (data) => {
  navigator.clipboard.writeText(data).then(
    function () {
      ElMessage.success("复制成功");
    },
    function () {}
  );
};
const resetSecret = () => {
  axios.get(`/apaas/system/v5/user/reset/secret/${props.id}`).then((res) => {
    if (res.data.code == 200) {
      systemForm.appsecret = res.data.data;
      ElMessage.success("重置成功！");
    } else {
      ElMessage.error(res.data.data);
    }
  });
};
const getRoleList = () => {
  axios.get(`/apaas/system/v5/org/select/role?is_admin=1`).then((res) => {
    if (res.data.code == 200) {
      roleList.value = res.data.data;
      systemForm.system_role_id = roleList.value[0].role_id;
    } else {
    }
  });
};

const getFirmList = () => {
  axios.get(`/apaas/system/v5/dictionary/developer/list`).then((res) => {
    if (res.data.code == 200) {
      firmList.value = res.data.data || [];
    } else {
      ElMessage.error(res.data.data);
    }
  });
};

onBeforeMount(() => {
  getOrgTree();
  getRoleList();
  getFirmList();
});

onMounted(() => {});

defineExpose({ submitForm, clearForm, setForm });
</script>
