<template>
  <div class="card-edit">
    <a-form :model="dataModel" autocomplete="off" @finish="onFinish">
      <a-divider orientation="left">站点人员管理</a-divider>
      <a-row type="flex">
        <a-col :span="7">
          <a-form-item label="姓名" name="siteUserName" :label-col="{span:7}" :rules="[{ required: true, message: '请输入人员姓名!' }]">
            <label v-if="opCategory==3">{{dataModel.siteUserName}}</label>
            <a-input v-model:value="dataModel.siteUserName" placeholder=""/>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="性别" name="gender" :label-col="{span:7}" :rules="[{required: true, message: '请选择人员性别!' }]">
            <label v-if="opCategory==3">{{dataModel.gender}}</label>
            <a-select ref="select" v-model:value="dataModel.gender" :options="genderList"
                      :field-names="{ label: 'name', value: 'value' }" :allow-clear="false" > </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="联系电话" name="mobile" :label-col="{span:8}" :rules="[{ required: true, message: '请输入联系电话!' }]" >
            <label v-if="opCategory==3">{{dataModel.mobile}}</label>
            <a-input v-model:value="dataModel.mobile" placeholder=""/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row type="flex">
        <a-col :span="7">
          <a-form-item label="工号" name="roleID" :label-col="{span:7}"
                       :rules="[{ required: true, message: '请输入工号!' }]">
            <label v-if="opCategory==3">{{ dataModel.userNo }}</label>
            <a-input v-model:value="dataModel.userNo" placeholder=""/>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="身份证" name="roleID" :label-col="{span:7}"
                       :rules="[{ required: true, message: '请输入身份证!' }]">
            <label v-if="opCategory==3">{{ dataModel.idCard }}</label>
            <a-input v-model:value="dataModel.idCard" placeholder=""/>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="用户类型" name="roleID" :label-col="{span:8}"
                       :rules="[{ required: true, message: '请选择用户类型!' }]">
            <label v-if="opCategory==3">{{ dataModel.roleID }}</label>
            <a-select ref="select" v-model:value="dataModel.roleID" :options="roleList"
                      :field-names="{ label: 'name', value: 'value' }" :allow-clear="false"></a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row type="flex">
        <a-col :span="7">
          <a-form-item label="所属驿站"  name="siteID" :label-col="{span:7}" :rules="[{ required: true, message: '请选择所属驿站!' }]">
            <a-select
              ref="select"
              v-model:value="dataModel.siteID"
              :options="allSites"
              :field-names="{ label: 'siteName', value: 'siteID' }" >
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-form-item class="buttom-btns">
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" html-type="submit">提交</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>
<script lang="ts">
import {defineComponent, reactive, ref, toRefs} from "vue";
import {useTabsViewStore} from "@/store/modules/tabsView";
import {getSiteUserByID, saveSiteUser} from "@/api/baseSettings/userInfo";
import BUploadFile from "@/components/file/uploadFile.vue";
import type {SelectProps} from "ant-design-vue";
import {message} from "ant-design-vue";
import {getSysDictionaryList} from "@/api/system/dictionary";
import {getSiteList} from "@/api/baseSettings/siteInfo";

interface siteUserModel {
  dataModel: any;
}

export default defineComponent({
  name:'UserInfoEditForm',
  components: {BUploadFile},
  props: {
    loadData: {
      type: Function,
      default: null
    }
  },
  setup() {
    const title = ref();
    const opCategory = ref<any>();
    const tabsViewStore = useTabsViewStore();
    const formData = reactive<siteUserModel>({ dataModel:{}});
    const isAllowCommit = ref<boolean>(true) ;
    const formState = reactive({
      total: 0,
      selectedRowKeys: [],
      loading: false
    });
    const allSites = ref<any>([]);
    const genderList = ref<SelectProps["options"]>();
    const roleList = ref<SelectProps["options"]>([]);

    const getAllSites = () => {
      getSiteList({pageIndex:1,pageSize:9999}).then((result :any) => {
        allSites.value = result.list;
      })
    }
    const getGenderList = async function(){
      const genderResult :any = await getSysDictionaryList("Gender");
      genderList.value = genderResult;
    }
    const getRoleList = async function(operateType:number){
      const roleResult :any = await getSysDictionaryList("UserType");
      roleList.value = operateType==1?[{name:"驿站工作者",value:3}]:roleResult;
      // console.log("roleList",roleList.value);
    }

    const loadData = (siteUserID: string,operateType:number) => {
      getAllSites();
      getGenderList();
      getRoleList(operateType);
      opCategory.value = operateType;
      getSiteUserByID(siteUserID).then((result: any) => {
        formData.dataModel = result;
        //console.log("dataModel",formData.dataModel);
      });
    };

    const onSelectChange = (selectedRowKeys: any) => {
      formState.selectedRowKeys = selectedRowKeys;
    };

    const mobileValidate = ()=>{
      isAllowCommit.value = true;
      const mobileReg = /^1[3|4|5|6|7|8|9]\d{9}$/;
      if(!mobileReg.test(formData.dataModel.mobile)){
        message.error("输入的联系电话有误!");
        isAllowCommit.value = false;
      }
    };

    function idCardValidate() {
      isAllowCommit.value = true;
      let _IDRe18 = /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
      let _IDre15 = /^([1-6][1-9]|50)\d{4}\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}$/
      // 校验身份证
      if (!_IDRe18.test(formData.dataModel.idCard) && !_IDre15.test(formData.dataModel.idCard)) {
        message.error("输入的身份证格式有误!");
        isAllowCommit.value = false;
      }
    }

    const onClose = (reload: any) => {
      tabsViewStore.closeCurrentTabByPath('/baseSettings/user/add');
      tabsViewStore.closeCurrentTabByPath('/baseSettings/user/edit');
      tabsViewStore.openTab('/baseSettings/user/index',{reload:reload});
    };

    const onFinish = () => {
      mobileValidate();
      idCardValidate();
      if(isAllowCommit.value){
        saveSiteUser(formData.dataModel).then(result => {
          if (result) {
            onClose(1);
          }
        });
      }

    };


    return {
      ...toRefs(formData),
      loadData,
      onClose,
      onFinish,
      title,
      formState,
      opCategory,
      isAllowCommit,
      allSites,
      genderList,
      roleList,
      onSelectChange,
    };
  },
  created() {
    const id = history.state.params?.id;
    const op = history.state.params?.op;
    this.loadData(id,op);
  },
})
</script>

