<template>
  <div class="edit-popup">
    <popup
      ref="popupRef"
      :title="popupTitle"
      :async="true"
      width="80%"
      @confirm="handleSubmit"
      @close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        label-width="84px"
        :rules="formRules"
      >
        <div style="font-size: 1.2rem; margin: 10px 0">基本信息创建</div>
        <div class="headimg">
          <el-upload
            :disabled="isCheck"
            v-model="formData.avatar"
            class="avatar-uploader-head"
            :data="{ cid: 1 }"
            :headers="{ Token: userStore.token }"
            :action="base_url + '/upload/image'"
            :show-file-list="false"
            :on-success="handleAvatarSuccessAvatar"
          >
            <img v-if="formData.avatar" :src="formData.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </div>
        <el-col class="pt-6 !border-none">
          <el-row>
            <el-col :span="11">
              <el-form-item label="姓名" prop="name">
                <el-input
                  :disabled="isCheck"
                  v-model="formData.name"
                  placeholder="请输入姓名"
                  clearable
                  :style="{ width: '100%' }"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="13">
              <el-form-item label="性别" prop="sex">
                <el-select
                  v-model="formData.sex"
                  placeholder="请选择性别"
                  :disabled="isCheck"
                  :style="{ width: '100%' }"
                >
                  <el-option label="男" value="1" />
                  <el-option label="女" value="2" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item label="身份证号" prop="id_card">
                <el-input
                  :disabled="isCheck"
                  v-model="formData.id_card"
                  placeholder="请输入身份证号"
                  clearable
                  :style="{ width: '100%' }"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="13">
              <el-form-item label="联系电话" prop="account">
                <el-input
                  :disabled="isCheck"
                  v-model="formData.account"
                  placeholder="请输入联系电话"
                  clearable
                  :style="{ width: '100%' }"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-form-item label="省" prop="province" style="flex: 1">
              <el-select
                :disabled="isCheck"
                v-model="formData.province"
                placeholder="请选择省"
                clearable
                @change="province_change"
                :style="{ width: '100%' }"
              >
                <el-option
                  v-for="(item, index) in datas.provinceOptions"
                  :key="index"
                  :label="item.province_name"
                  :value="item.province_code"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="市" prop="city" style="flex: 1">
              <el-select
                :disabled="isCheck"
                v-model="formData.city"
                placeholder="请选择市"
                clearable
                @change="city_change"
                :style="{ width: '100%' }"
              >
                <el-option
                  v-for="(item, index) in datas.cityOptions"
                  :key="index"
                  :label="item.city_name"
                  :value="item.city_code"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="区" prop="area" style="flex: 1">
              <el-select
                :disabled="isCheck"
                v-model="formData.area"
                placeholder="请选择区"
                clearable
                @change="area_change"
                :style="{ width: '100%' }"
              >
                <el-option
                  v-for="(item, index) in datas.areaOptions"
                  :key="index"
                  :label="item.area_name"
                  :value="item.area_code"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item
              v-if="disabledPartyA"
              label="镇"
              prop="street"
              style="flex: 1"
            >
              <el-select
                :disabled="isCheck"
                v-model="formData.street"
                placeholder="请选择镇"
                clearable
                @change="street_change"
                :style="{ width: '100%' }"
              >
                <el-option
                  v-for="(item, index) in datas.streetOptions"
                  :key="index"
                  :label="item.street_name"
                  :value="item.street_code"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              v-if="disabledPartyA"
              label="村社小队"
              prop="address"
              style="flex: 1.5"
            >
              <el-input
                :disabled="isCheck"
                v-model="formData.address"
                placeholder="请输入村社小队"
                clearable
                :style="{ width: '100%' }"
              ></el-input>
            </el-form-item>
          </el-row>
        </el-col>

        <el-col :span="24" style="margin-top: 1vh">
          <el-row>
            <el-col :span="12">
              <el-form-item label="授权身份" prop="role_id">
                <el-select
                  v-model="formData.role_id"
                  :disabled="formData.root == 1 || isCheck"
                  placeholder="请选择授权身份"
                  :style="{ width: '100%' }"
                  @change="role_change"
                  clearable
                >
                  <el-option
                    v-if="formData.root == 1"
                    label="系统管理员"
                    :value="0"
                  />
                  <el-option
                    v-for="(item, index) in optionsData.role"
                    :key="index"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
      </el-form>
    </popup>
    <el-dialog v-model="isCompany" title="选择签约方" width="60%">
      <DialogIndex @customEvent="customEvent" />
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import type {
  FormInstance,
  UploadProps,
  ElMessage,
  UploadUserFile,
} from "element-plus";
import Popup from "@/components/popup/index.vue";
import { useDictOptions } from "@/hooks/useDictOptions";
import { adminAdd, adminDetail, adminEdit } from "@/api/perms/admin";
import { roleAll } from "@/api/perms/role";
import { jobsAll } from "@/api/org/post";
import { deptAll } from "@/api/org/department";
import {
  apiCityList,
  apiAreaList,
  apiStreetList,
  apiProvinceList,
} from "@/api/common";
import { dictDataLists } from "@/api/setting/dict";
import DialogIndex from "./dialog_index.vue";
import useUserStore from "@/stores/modules/user";
import { inject } from "vue";
const base_url: any = inject("base_url");
const disabledPartyA = ref(true);
const isCheck = ref(false);
const isCheckFn = (flag: boolean) => {
  isCheck.value = flag;
};
const emit = defineEmits(["success", "close"]);
const formRef = shallowRef<FormInstance>();
const popupRef = shallowRef<InstanceType<typeof Popup>>();
const mode = ref("add");
const popupTitle = computed(() => {
  return mode.value == "edit" ? "编辑管理员" : "新增管理员";
});
const formData = reactive({
  id: "",
  sex: "",
  id_card: "",
  name: "",
  province: "",
  city: "",
  area: "",
  street: "",
  address: "",
  account: "",
  is_contract: 0,
  // 签约方
  party_a_name: "",
  party_a: "",
  qualification: {
    id_card: "",
    id_card_b: "",
    car_card: "",
    car_card_b: "",
    bank_account: "",
    bank_account_b: "",
  },
  // 合同类型
  contract_type: "",
  file: "",
  role_id: "",
  avatar: "",
  multipoint_login: 1,
  root: 0,
  disable: 0,
  contract: {
    url: "",
  },
});
// 字典信息
const datas: any = reactive({
  provinceOptions: [],
  cityOptions: [],
  areaOptions: [],
  streetOptions: [],
  dictTypeLists: [],
  contract_type: [],
  contract: [],
});
const userStore = useUserStore();
const getcontract_type = async () => {
  const data = await dictDataLists({ type_id: 7 });
  datas["contract_type"] = data["lists"];
};
getcontract_type();

const isCompany = ref(false);
function customEvent(data: any) {
  isCompany.value = false;
  formData.party_a = data.id;
  formData.party_a_name = data.company_name;
}
function clearPartyA() {
  formData.party_a = "";
  formData.party_a_name = "";
}
// 表单验证
// 手机号校验
const ValidatorPhone = (rule: object, value: string, callback: any) => {
  const rg = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;
  rg.test(formData.account)
    ? callback()
    : callback(new Error("请输入正确的手机号"));
};
// 身份证校验
const ValidatorId = (rule: object, value: string, callback: any) => {
  const rg =
    /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/;
  rg.test(formData.id_card)
    ? callback()
    : callback(new Error("请输入正确的身份证号码"));
};
const Validatorcard = (rule: object, value: string, callback: any) => {
  formData.qualification.car_card
    ? callback()
    : callback(new Error("请输入驾驶证正面"));
};
const ValidatorcardB = (rule: object, value: string, callback: any) => {
  formData.qualification.car_card_b
    ? callback()
    : callback(new Error("请输入驾驶证反面"));
};
const ValidatorBankcard = (rule: object, value: string, callback: any) => {
  formData.qualification.bank_account
    ? callback()
    : callback(new Error("请输入银行卡正面"));
};
const ValidatorBankcardB = (rule: object, value: string, callback: any) => {
  formData.qualification.bank_account_b
    ? callback()
    : callback(new Error("请输入银行卡反面"));
};
function role_change(e: any) {
  if (e == 8) {
    disabledPartyA.value = false;
    formData.party_a = "";
  } else {
    disabledPartyA.value = true;
  }
}
const formRules = reactive({
  account: [
    {
      required: true,
      trigger: ["blur"],
      validator: ValidatorPhone,
    },
  ],
  id_card: [
    {
      required: true,
      trigger: ["blur"],
      validator: ValidatorId,
    },
  ],
  sex: [
    {
      required: true,
      message: "请选择性别",
      trigger: ["blur"],
    },
  ],

  name: [
    {
      required: true,
      message: "请输入名称",
      trigger: ["blur"],
    },
  ],
  car_card: [
    {
      required: true,
      trigger: ["change"],
      validator: Validatorcard,
    },
  ],
  car_card_b: [
    {
      required: true,
      trigger: ["blur"],
      validator: ValidatorcardB,
    },
  ],
  bank_account: [
    {
      required: true,
      trigger: ["change"],
      validator: ValidatorBankcard,
    },
  ],
  bank_account_b: [
    {
      required: true,
      trigger: ["change"],
      validator: ValidatorBankcardB,
    },
  ],
  role_id: [
    {
      required: true,
      message: "请选择角色",
      trigger: ["blur"],
    },
  ],
});
// 表单验证结束
const { optionsData } = useDictOptions<{
  role: any[];
  jobs: any[];
  dept: any[];
}>({
  role: {
    api: roleAll,
  },
  jobs: {
    api: jobsAll,
  },
  dept: {
    api: deptAll,
  },
});
const handleSubmit = async () => {
  if (isCheck.value) {
    popupRef.value?.close();
    return;
  }
  await formRef.value?.validate();
  mode.value == "edit"
    ? await adminEdit(formData)
    : await adminAdd(formData).then((res) => console.log(res));
  popupRef.value?.close();
  emit("success");
};
const open = (type = "add") => {
  mode.value = type;
  popupRef.value?.open();
  if (type == "view") {
    isCheck.value = true;
  }
};
const fileList = ref<UploadUserFile[]>([]);
// 图片上传成功返回的url
const handleAvatarSuccessIdA: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  if (response.code == 0) {
    ElMessage.error(response.msg);
    return;
  }
  formData.qualification.id_card = response.data.uri;
};
const handleAvatarSuccessAvatar: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  if (response.code == 0) {
    ElMessage.error(response.msg);
    return;
  }
  formData.avatar = response.data.uri;
};
const handleAvatarSuccessIdB: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  if (response.code == 0) {
    ElMessage.error(response.msg);
    return;
  }
  formData.qualification.id_card_b = response.data.uri;
};
const handleAvatarSuccessCarA: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  if (response.code == 0) {
    ElMessage.error(response.msg);
    return;
  }
  formData.qualification.car_card = response.data.uri;
};
const handleAvatarSuccessCarB: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  if (response.code == 0) {
    ElMessage.error(response.msg);
    return;
  }
  formData.qualification.car_card_b = response.data.uri;
};
const beforeAvatarUpload_two: UploadProps["beforeUpload"] = (rawFile) => {
  return true;
};
const handleAvatarSuccessBankA: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  if (response.code == 0) {
    ElMessage.error(response.msg);
    return;
  }
  formData.qualification.bank_account = response.data.uri;
};
const handleAvatarSuccessBankB: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  if (response.code == 0) {
    ElMessage.error(response.msg);
    return;
  }
  formData.qualification.bank_account_b = response.data.uri;
};
const handleAvatarSuccess_four: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  if (response.code == 0) {
    ElMessage.error(response.msg);
    return;
  }
  formData.file = response.data.uri;

  fileList.value[0].url = response.data.uri;
  fileList.value[0].name = "合同文件";
};
const beforeAvatarUpload_three: UploadProps["beforeUpload"] = (rawFile) => {
  return true;
};

//获取省份
function province_change(value: string) {
  getCityList();
}
function city_change(value: string) {
  getAreaList();
}
function area_change(value: string) {
  getStreetList();
}
function street_change(value: string) {
  formData.street = value;
}
const getProvinceList = async () => {
  const data = await apiProvinceList({});
  datas["provinceOptions"] = data;
};
const getCityList = async () => {
  const data = await apiCityList({ city: formData.province });
  datas["cityOptions"] = data;
};
const getAreaList = async () => {
  const data = await apiAreaList({ area: formData.city });
  datas["areaOptions"] = data;
};
const getStreetList = async () => {
  const data = await apiStreetList({ street: formData.area });
  datas["streetOptions"] = data;
};
getProvinceList();

const setFormData = async (row: any) => {
  const data = await adminDetail({
    id: row.id,
  });
  for (const key in formData) {
    const stringArr = ["sex", "province", "city", "area", "street"];
    if (data[key] != null && data[key] != undefined) {
      //@ts-ignore
      key == "role_id"
        ? (formData[key] = data[key][0])
        : (formData[key] = data[key]);
      if (stringArr.includes(key)) formData[key] = formData[key].toString();
    }
  }
  formData.contract_type = data.contract?.contract_type;
  formData.party_a_name = data.contract?.party_a_name;
  formData.party_a = data.contract?.party_a;
  formData.file = data.contract?.file;
  if (data.role_id[0] == 8) {
    disabledPartyA.value = false;
  }
  fileList.value[0] = {
    url: data.contract?.file,
    name: "合同文件",
  };
  await getCityList();
  await getAreaList();
  await getStreetList();
};
const handleClose = () => {
  emit("close");
};
defineExpose({
  open,
  setFormData,
  isCheckFn,
});
</script>

<style lang="scss">
.headimg {
  margin-top: 24px;
  width: 6.2vw;
  height: 7.2vw;
  float: left;
  overflow: hidden;
}

.avatar-uploader-head .el-upload {
  width: 6.2vw;
  height: 7.2vw;
  background-color: #fff;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload {
  width: 9.9vw;
  height: 6.3vw;
  background-color: #fff;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
