<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="siteCode" :label-col="{span:7}" :rules="[{ required: true, message: '请输入驿站编号!' }]">
            <label v-if="opCategory==3">{{dataModel.siteCode}}</label>
            <a-input v-model:value="dataModel.siteCode" placeholder=""/>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="站点名称" name="siteName" :label-col="{span:7}" :rules="[{ required: true, message: '请输入站点名称!' }]">
            <label v-if="opCategory==3">{{dataModel.siteName }}</label>
            <a-input v-model:value="dataModel.siteName" placeholder=""/>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="所属机构" name="institutionID" :label-col="{span:7}" :rules="[{ required: true, message: '请选择所属机构!' }]">
            <label v-if="opCategory==3">{{dataModel.institutionID}}</label>
            <a-select  ref="select" v-model:value="dataModel.institutionID" :options="institutionList"
                      :field-names="{ label: 'text', value: 'value' }" :allow-clear="true" > </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row type="flex">
        <a-col :span="7">
          <a-form-item label="所属县区"  name="regionCode" :label-col="{span:7}" :rules="[{ required: true, message: '请选择所属县区!' }]">
            <label v-if="opCategory==3">{{dataModel.regionCode}}</label>
            <a-select ref="select" v-model:value="dataModel.regionCode" :options="regionList"
              :field-names="{ label: 'name', value: 'code' }" :allow-clear="true" @change="regionChange" > </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="所属街道"  name="streetCode" :label-col="{span:7}" :rules="[{ required: true, message: '请选择所属街道!' }]">
            <label v-if="opCategory==3">{{dataModel.streetCode }}</label>
            <a-select ref="select" v-model:value="dataModel.streetCode" :options="streetList"
              :field-names="{ label: 'name', value: 'code' }" :allow-clear="true" > </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="详细地址"  name="detailAddress" :label-col="{span:7}" :rules="[{ required: true, message: '请输入详细地址!' }]">
            <label v-if="opCategory==3">{{dataModel.detailAddress }}</label>
            <a-input v-model:value="dataModel.detailAddress" placeholder=""/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row type="flex">
        <a-col :span="7">
          <a-form-item label="站点负责人"  name="fzrName" :label-col="{span:7}" :rules="[{ required: true, message: '请输入站点负责人!' }]">
            <label v-if="opCategory==3">{{dataModel.fzrName }}</label>
            <a-input v-model:value="dataModel.fzrName" placeholder=""/>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="联系电话"  name="fzrMobile" :label-col="{span:7}" :rules="[{ required: true, message: '请输入联系电话!' }]">
            <label v-if="opCategory==3">{{dataModel.fzrMobile }}</label>
            <a-input v-model:value="dataModel.fzrMobile" placeholder=""/>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="经度"  name="siteLongitude" :label-col="{span:7}" :rules="[{ required: true, message: '请输入经度!' }]">
            <label v-if="opCategory==3">{{dataModel.siteLongitude }}</label>
            <a-input-number style="width: 100%" :controls="false" v-model:value="dataModel.siteLongitude" placeholder=""/>
          </a-form-item>
        </a-col>
<!--        <a-col :span="8">-->
<!--          <a-form-item label="驿站坐标"  name="sitePosition" :label-col="{span:7}" :rules="[{ required: true, message: '请选择驿站坐标!' }]">-->
<!--            <label v-if="opCategory==3">{{dataModel.sitePosition}}</label>-->
<!--            <a-input v-model:value="dataModel.sitePosition" placeholder=""/>-->
<!--          </a-form-item>-->
<!--        </a-col>-->
<!--        <a-col :span="1">-->
<!--            <a-button type="primary"  @click='' >选择</a-button>-->
<!--        </a-col>-->
      </a-row>
      <a-row type="flex">
        <a-col :span="7">
          <a-form-item label="纬度"  name="siteLatitude" :label-col="{span:7}" :rules="[{ required: true, message: '请输入站点负责人!' }]">
            <label v-if="opCategory==3">{{dataModel.siteLatitude }}</label>
            <a-input-number style="width: 100%" :controls="false" v-model:value="dataModel.siteLatitude" placeholder=""/>
          </a-form-item>
        </a-col>
      </a-row>
<!--      <a-divider orientation="left">管理人员 共计：{{manageUsers.length}}</a-divider>
      <a-row>
        <a-col :span="24" style="text-align: right; margin-top: 20px; margin-right: 20px">
          <Space>
            <a-button @click="addSiteUser">
              <template #icon>
                <plus-circle-outlined/>
              </template>
              新增
            </a-button>
          </Space>
        </a-col>
      </a-row>
      <a-row>
        <a-col style="margin-bottom: 20px;">
          <a-table :columns="columns" :data-source="manageUsers" :pagination="pagination"
                   :loading="formState.loading"
                   @change="handleTableChange"
                   :row-selection="{ selectedRowKeys: formState.selectedRowKeys, onChange: onSelectChange}"
                   :row-key="record=>record.siteId"
                   bordered>
            <template #bodyCell="{ column ,index}">
              <template v-if="column.key === 'siteUserName'">
                <div>
                  <a-select
                    ref="select"
                    v-model:value="manageUsers[index][column.key]"
                    :options="allUsers"
                    @change="manageUsersChange(index,manageUsers[index][column.key])"
                    :field-names="{ label: 'siteUserName', value: 'siteUserID' }" style="width: 200px" >
                  </a-select>
                </div>
              </template>
              <template v-if="column.key === 'genderName'">
                {{manageUsers[index][column.key]}}
              </template>
              <template v-if="column.key === 'roleName'">
                {{manageUsers[index][column.key]}}
              </template>
              <template v-if="column.key === 'operation'">
                <a-button type="link" size="small" @click="delSiteUser(index)">删除</a-button>
              </template>
            </template>
          </a-table>
        </a-col>
      </a-row>-->
      <a-divider orientation="left">其他信息</a-divider>
      <a-row>
        <a-textarea :auto-size="{ minRows: 4, maxRows: 10 }"  v-model:value="dataModel.remark"  :disabled="opCategory==3"
                    placeholder="备注" />
      </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 {computed, defineComponent, reactive, ref, toRefs} from "vue";
import {useTabsViewStore} from "@/store/modules/tabsView";
import {getSiteByID, saveSite} from "@/api/baseSettings/siteInfo";
import BUploadFile from "@/components/file/uploadFile.vue";
import {message, SelectProps, TableColumnsType, TableProps} from "ant-design-vue";
import {getRegionCodeList, getStreetCodeList} from "@/api/system/area/index";
import {getSiteUserList,getSiteUserDataList,getListBySiteID} from "@/api/baseSettings/userInfo";
import {getInstitutionDataList} from "@/api/baseSettings/institution";
import {getPaginationTotalTitle} from "@/utils/common";

interface siteModel {
  dataModel: any;
}
export default defineComponent({
  name:'SiteInfoEditForm',
  components: {BUploadFile},
  props: {
    loadData: {
      type: Function,
      default: null
    }
  },
  setup() {
    const title = ref();
    const opCategory = ref<any>();
    const tabsViewStore = useTabsViewStore();
    const isAllowCommit = ref<boolean>(false);
    const formState = reactive({
      total: 0,
      selectedRowKeys: [],
      loading: false
    });
    const formData = reactive<siteModel>({ dataModel:{}});
    const pageParams = reactive({
      pageIndex: 1,
      pageSize: 10,
      siteID:''
    });
    const columns: TableColumnsType = [
      {title: '序号', align: "center",key: 'siteUserID',customRender: item => `${pageParams.pageSize * (pageParams.pageIndex - 1) + item.index + 1}`},
      {title: '姓名', dataIndex: 'siteUserName', key: 'siteUserName', align: "center"},
      {title: '性别', dataIndex: 'genderName', key: 'genderName', align: "center"},
      {title: '角色', dataIndex: 'roleName', key: 'roleName', align: "center"},
      {title: '操作', key: 'operation', fixed: 'right',width:170, align: "center"},
    ];
    const pagination = computed(() => ({
      total: formState.total,
      current: pageParams.pageIndex,
      pageSize: pageParams.pageSize,
      showSizeChanger: true,
      showTotal: total => getPaginationTotalTitle(total)
    }));
    const onSelectChange = (selectedRowKeys: any) => {
      formState.selectedRowKeys = selectedRowKeys;
    };
    const handleTableChange: TableProps['onChange'] = (pag: { pageSize: number; current: number },) => {
      pageParams.pageIndex = pag.current;
      pageParams.pageSize = pag.pageSize;
    };

    const regionList = ref<SelectProps['options']>();
    const streetList = ref<SelectProps['options']>();
    const siteUserList = ref<SelectProps['options']>();
    const institutionList = ref<SelectProps["options"]>();

    const manageUsers = ref<any>([]);
    const allUsers = ref<any>([]);

    const getRegionList = async function(){
      const regionResult: any = await getRegionCodeList();
      regionList.value = regionResult;
    }
    const getStreetList = async function(){
      const streetResult: any = await getStreetCodeList(formData.dataModel.regionCode);
      streetList.value = streetResult;
    }
    const regionChange = async function(){
      formData.dataModel.streetCode = null;
      await getStreetList();
    }
    const getUserDataList = async function(){
      const siteUserResult :any = await getSiteUserDataList();
      // console.log('siteUserResult',siteUserResult);
      siteUserList.value = siteUserResult;
    }
    const getInstitutionList = async function(){
      const institutionResult :any = await getInstitutionDataList();
      // console.log('institutionResult',institutionResult);
      institutionList.value = institutionResult;
    }

    const loadData = (siteID: any) => {
      getAllUsers();
      getRegionList();
      getInstitutionList();
      getUserDataList();
      getSiteByID(siteID).then((result: any) => {
        formData.dataModel = result;
        //console.log("dataModel",formData.dataModel);
        getManageUsers(formData.dataModel.siteID);
        // console.log("manageUsers",manageUsers.value);
        if (formData.dataModel.regionCode != null){
          getStreetList();
        }
        if (formData.dataModel.siteX !=null && formData.dataModel.siteY != null){
          formData.dataModel.sitePosition = "X:"+formData.dataModel.siteX+" Y:"+formData.dataModel.siteX;
        }
      });
    }

    const getAllUsers = () => {
      pageParams.siteID = '';
      getSiteUserList(pageParams).then((result :any) => {
        allUsers.value = result.list;
        // console.log('allUsers',allUsers);
      })
    }
    const getManageUsers = (id: string) => {
      pageParams.siteID = id;
      getListBySiteID(pageParams).then((result :any)=> {
        manageUsers.value = result.list;
      });
    }

    /*const addSiteUser = () => {
      if(allUsers.value.length >0){
        const newUser = allUsers.value[0];
        // console.log(newUser);
        (manageUsers.value as any[]).push({siteUserID:newUser.siteUserID,siteID:formData.dataModel.siteID,siteUserName:newUser.siteUserName,genderName:newUser.genderName,roleName:newUser.roleName});
        validateSameUser();
      }else{
        message.error("未查询到站点信息!");
      }
    }
    const delSiteUser = (site) =>{
      (manageUsers.value as any[]).splice(site, 1);
      validateSameUser();
    }*/
    /*const manageUsersChange = (index:any,siteUserID:any) =>{
      // console.log('siteUserID',siteUserID);
      getSiteUserByID(siteUserID).then((result :any)=> {
        result.siteID = formData.dataModel.siteID;
        manageUsers.value[index]= result;
        // console.log('manageUsers',manageUsers.value);
        validateSameUser();
      });
    }*/

   /* const validateSameUser = ()=>{
      isAllowCommit.value = true;
      if (manageUsers.value.length>1){
        manageUsers.value.forEach(item=>{
          const sameData = manageUsers.value.filter(x => x.siteUserID == item.siteUserID);
          // console.log("sameData",sameData);
          if (sameData.length >1){
            isAllowCommit.value = false;
          }
        });
      }
      if (!isAllowCommit.value)message.error("不允许添加相同的人员!");
    }*/

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

    const onClose = (reload: any) => {
      tabsViewStore.closeCurrentTabByPath('/baseSettings/site/add');
      tabsViewStore.closeCurrentTabByPath('/baseSettings/site/edit');
      tabsViewStore.openTab('/baseSettings/site/index',{reload:reload});
    };
    const onFinish = () => {
      mobileValidate();
      /*validateSameUser();*/
      if (isAllowCommit.value){
        formData.dataModel.manageUsers = manageUsers.value;
        saveSite(formData.dataModel).then(result => {
          if (result) {
            onClose(1);
          }
        });
      }
    };



    return {
      ...toRefs(formData),
      loadData,
      onClose,
      onFinish,
      title,
      opCategory,
      formState,
      isAllowCommit,
      columns,
      pageParams,
      pagination,
      regionList,
      streetList,
      siteUserList,
      institutionList,
      allUsers,
      manageUsers,
      onSelectChange,
      handleTableChange,
      regionChange,
      getRegionList,
      getStreetList,
      getUserDataList,
      getInstitutionList,
      getAllUsers,
      /*addSiteUser,
      delSiteUser,
      manageUsersChange,*/
    };
  },
  created() {
    const id = history.state.params?.id;
    this.loadData(id);
  },
})
</script>

