<template>
  <a-modal
    :width="1200"
    v-model:visible="visible"
    :title="title"
    :confirm-loading="confirmLoading"
    @ok="handleOk"
    ok-text="提交"
    @cancel="handleCancel"
    cancel-text="取消"
    :keyboard="false"
    :mask-closable="false"  >
    <a-form  autocomplete="off" >
      <a-divider orientation="left">基础信息管理</a-divider>
      <a-row type="flex">
        <a-col :span="7">
          <a-form-item label="企业名称" name="CompanyName" :label-col="{span:7}">
            <label v-if="isDetail">{{dataModel.companyName}}</label>
            <a-input v-model:value="dataModel.companyName" placeholder=""/>
          </a-form-item>
        </a-col>
        <a-col :span="7">
          <a-form-item label="企业地址" name="CompanyAddress" :label-col="{span:7}">
            <label v-if="isDetail">{{dataModel.companyAddress }}</label>
            <a-input v-model:value="dataModel.companyAddress" placeholder=""/>
          </a-form-item>
        </a-col>
        <a-col :span="10">
          <a-form-item label="负责人姓名" name="DutyUserName" :label-col="{span:10}" >
            <label v-if="isDetail">{{dataModel.fzrName}}</label>
            <a-input v-model:value="dataModel.fzrName" placeholder=""/>
<!--            <a-date-picker  name="feedbackDate2" v-model:value="dataModel.feedbackDate"   value-format="YYYY-MM-DD" picker="date"
                            placeholder="请选择问题反馈日期"  v-if="!isDetail"  />
                <a-select  ref="select" v-model:value="dataModel.problemCharacteristics"
                                   :options="problemAttrList"  :field-names="{label:'name',value:'value'}"
                                   @change="loadData"  :allow-clear="true"  v-if="!isDetail">
                        </a-select>-->
          </a-form-item>
        </a-col>
      </a-row>
      <a-row type="flex">
        <a-col :span="7">
          <a-form-item label="负责人电话"  name="DutyUserMobile" :label-col="{span:7}">
            <label v-if="isDetail">{{dataModel.fzrMobile }}</label>
            <a-input v-model:value="dataModel.fzrMobile" placeholder=""/>
          </a-form-item>
        </a-col>
        <a-col :span="7">
          <a-form-item label="法人姓名"  name="LegalerName" :label-col="{span:7}">
            <label v-if="isDetail">{{dataModel.frName }}</label>
            <a-input v-model:value="dataModel.frName" placeholder=""/>
          </a-form-item>
        </a-col>
        <a-col :span="10">
          <a-form-item label="法人电话"  name="LegalerMobile" :label-col="{span:10}">
            <label v-if="isDetail">{{dataModel.frMobile }}</label>
            <a-input v-model:value="dataModel.frMobile" placeholder=""/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row type="flex">
        <a-col :span="7">
          <a-form-item label="企业机构代码"  name="CompanyCode" :label-col="{span:7}">
            <label v-if="isDetail">{{dataModel.companyCode }}</label>
            <a-input v-model:value="dataModel.companyCode" placeholder=""/>
          </a-form-item>
        </a-col>
        <a-col :span="7"></a-col>
        <a-col :span="10"></a-col>
      </a-row>
      <a-divider orientation="left">管理驿站 共计：{{manageSites.length}}</a-divider>
      <a-row>
        <a-col :span="24" style="text-align: right; margin-top: 20px; margin-right: 20px">
          <Space>
            <a-button @click="addSite">
              <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="manageSites" :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 === 'siteName'">
                <div>
                  <a-select
                    ref="select"
                    v-model:value="manageSites[index][column.key]"
                    :options="allSites"
                    @change="manageSitesChange(index,manageSites[index][column.key])"
                    :field-names="{ label: 'siteName', value: 'siteID' }"
                    :allow-clear="true" style="width: 200px" >
                  </a-select>
                </div>
              </template>
              <template v-if="column.key === 'detailAddress'">
                   {{manageSites[index][column.key]}}
              </template>
              <template v-if="column.key === 'operation'">
                <a-button type="link" size="small" @click="delSite(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.companyDesc"  :disabled="isDetail"
                    placeholder="企业简介" style="text-align: center;" />
      </a-row>
      <a-row style="height: 10px"></a-row>
      <a-row>
        <a-textarea :auto-size="{ minRows: 4, maxRows: 10 }"  v-model:value="dataModel.remarkDesc"  :disabled="isDetail"
                    placeholder="备注" style="text-align: center;" />
      </a-row>
    </a-form>
  </a-modal>
</template>
<script lang="ts">
import {computed, defineComponent, reactive, ref, toRefs} from "vue";
import {getInstitutionByID, saveInstitution} from "@/api/baseSettings/institution";
import {getSiteList,getListByInstitutionID,getSiteByID} from "@/api/baseSettings/siteInfo";
import BUploadFile from "@/components/file/uploadFile.vue";
import {message, TableColumnsType, TableProps} from "ant-design-vue";
import {getPaginationTotalTitle} from "@/utils/common";
/*import dayjs from "dayjs";*/

interface InstitutionModel {
  dataModel: any;
}
export default defineComponent({
  name:'InstitutionEditForm',
  components: {BUploadFile},
  props: {
    loadData: {
      type: Function,
      default: null
    }
  },
  setup(props) {
    /*const feedbackDateDetail = ref();
    const resolveDateDetail = ref();*/
    const formData = reactive<InstitutionModel>({ dataModel:{}});
    const visible = ref<boolean>(false);
    const confirmLoading = ref<boolean>(false);
    const title = ref();
    const isAllowCommit = ref<boolean>(false);
    const isDetail = ref<boolean>(false);
    const pageParams = reactive({
      pageIndex: 1,
      pageSize: 10,
      institutionID:''
    });
    const columns: TableColumnsType = [
      {title: '序号', align: "center",key: 'siteID',customRender: item => `${pageParams.pageSize * (pageParams.pageIndex - 1) + item.index + 1}`},
      {title: '驿站名称', dataIndex: 'siteName', key: 'siteName', align: "center"},
      {title: '驿站地址', dataIndex: 'detailAddress', key: 'detailAddress', 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 formState = reactive({
      total: 0,
      selectedRowKeys: [],
      loading: false
    });
    const allSites = ref([]);
    const manageSites = ref<any>([]);

    const loadData = (id: string) => {
      getInstitutionByID(id).then((result: any) => {
        formData.dataModel = result;
        console.log('dataModel',formData.dataModel);
        GetManageSites(formData.dataModel.institutionID);
        /*feedbackDateDetail.value = dayjs(formState.dataModel.feedbackDate).format('YYYY-MM-DD');
        resolveDateDetail.value = formState.dataModel.resolveDate == null?"": dayjs(formState.dataModel.resolveDate).format('YYYY-MM-DD');*/
      });
    }

    const show = (id: any,method:string,ifDetail:boolean) => {
      title.value ="运营机构管理-"+method;
      isDetail.value = ifDetail;
      loadData(id);
      visible.value = true;
    };

    const getAllSites = () => {
      pageParams.institutionID = '';
      getSiteList(pageParams).then((result :any) => {
        allSites.value = result.list;
        console.log('allSites',allSites);
      })
    }

    const GetManageSites = (id: string) => {
      pageParams.institutionID = id;
      getListByInstitutionID(pageParams).then((result :any)=> {
          manageSites.value = result.list;
          console.log('manageSites',manageSites);
      });
    }

    const addSite = () => {
      (manageSites.value as any[]).push({siteID: null,siteName: '', detailAddress:''});
    }
    const delSite = (site) =>{
      (manageSites.value as any[]).splice(site, 1);
    }

    const handleTableChange: TableProps['onChange'] = (pag: { pageSize: number; current: number },) => {
      pageParams.pageIndex = pag.current;
      pageParams.pageSize = pag.pageSize;
    };

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

    const manageSitesChange = (index:any,siteID:any) =>{
      const isAllowAdd = ref<boolean>(true);
      manageSites.value.forEach(item=>{
        if (item.siteID == siteID){
          isAllowAdd.value = false;
          return;
        }
      });
      if (isAllowAdd.value){
        getSiteByID(siteID).then((result :any)=> {
          manageSites.value[index]= result;
        });
        console.log('manageSites',manageSites.value);
      }else{
        (manageSites.value as any[]).splice(index, 1);
        message.error("不允许添加相同的站点!");
      }
    }

    const validate = ()  =>{
      console.log('dataModel',formData.dataModel);
      if (formData.dataModel.companyName==null) {
        message.error("请输入企业名称!");
        return;
      }else if (formData.dataModel.companyAddress==null) {
        message.error("请输入企业地址!");
        return;
      }else if (formData.dataModel.fzrName==null) {
        message.error("请输入负责人名称!");
        return;
      }else if (formData.dataModel.fzrMobile==null) {
        message.error("请填写负责人电话!");
        return;
      }else if (formData.dataModel.frName==null) {
        message.error("请填写法人姓名!");
        return;
      }else if (formData.dataModel.frMobile==null) {
        message.error("请填写法人电话!");
        return;
      }else if (formData.dataModel.companyCode==null) {
        message.error("请填写企业机构代码!");
        return;
      }
      isAllowCommit.value = true;
    };

    const handleOk = () => {
      validate();
      if (isAllowCommit.value){
        formData.dataModel.manageSites = manageSites.value;
        saveInstitution(formData.dataModel).then(result => {
          if (result) {
            visible.value = false;
            props.loadData();
          }
        });
      }
    };

    const handleCancel = () => {
      visible.value = false;
    };

    return {
      ...toRefs(formData),
      pageParams,
      columns,
      pagination,
      formState,
      allSites,
      manageSites,
      /*feedbackDateDetail,
      resolveDateDetail,*/
      isAllowCommit,
      isDetail,
      visible,
      title,
      confirmLoading,
      show,
      getAllSites,
      GetManageSites,
      addSite,
      delSite,
      handleTableChange,
      onSelectChange,
      manageSitesChange,
      handleOk,
      handleCancel,
      validate
    };
  },
  created() {
    this.getAllSites();
  },
})
</script>

