<template>
 <div class="position-re">
   <my-breadcrumb class="my-breadcrumb" :breadcrumb-arr="myBreadArr"/>
   <div class="back" @click="$emit('changeOperation','',{})"><span class="fa fa-reply cur-po " >返回</span></div>
   <div class="my-detail-main">
     <div class="block">
        <div class="my-b-title">单位信息</div>
        <diy-el-form ref="unitFormRef" :forms="unitManageDetailFormConfig" v-model:model-form="form"/>
     </div>
     <div class="block" v-if="tabName === 'zw'">
       <div class="my-b-title">行政级别</div>
       <diy-el-form ref="rankFormRef" :forms="xzRankDetailFormConfig" v-model:model-form="form"/>
     </div>
   </div>

   <div class="detail-operation-btn" v-if="operationType!=='detail'">
     <el-button :icon="Select" @click="saveInfo">保存</el-button>
     <el-button :icon="Close" @click="$emit('changeOperation','')">关闭</el-button>
   </div>
   <template v-if="isIndustaryDialogIsShow">
     <unit-manage-industary-dialog :detail-form="{
       ...form,
     }" @getDialogInfo="getDialogInfo" :current-dialog-obj="currentObObj" v-model:dialog-visible="isIndustaryDialogIsShow"></unit-manage-industary-dialog>
   </template>
 </div>
</template>

<script>
import MyBreadcrumb from "@/components/common/MyBreadcrumb.vue";
import DiyElForm from "@/components/common/DiyElForm.vue";
import {computed, onBeforeMount, onMounted, ref, watch} from "vue";
import {unitManageDetailForm, unitManageDetailFormZw, xzRankDetailForm} from "@/data/all-forms";
import {Close, Select} from "@element-plus/icons-vue";
import {
  addUnitInfoSpace, addUnitInfoZw, editUnitInfoSpace, editUnitInfoZw,
  getDetailUnitListSpace, getDetailUnitListZw, getUnitManageDetailAllIndustry,
  getUnitManageDetailTableDataSpace, getUnitManageDetailTableDataZw, getZwUnitSetRegion, getZwUnitSpaceArea
} from "@/service/system-manage/unit-manage/unit-maneg";
import {staTabReflectArr} from "@/data/all-reflect";
import UnitManageIndustaryDialog
  from "@/view/other/c-views/system-manage/system-manage/unit-manage/UnitManageIndustaryDialog.vue";
import {useRootStore} from "@/stores/useStore";
import {handleMes} from "@/unit/element-ui/tip";
import {isValid} from "js-base64";

export default {
  name: "UnitManageDetail",
  computed: {
    Close() {
      return Close
    },
    Select() {
      return Select
    }
  },
  props:{
    currentObObj:{

    },
    tabName:{

    },
    operationType:{}

  },
  components: {UnitManageIndustaryDialog, DiyElForm, MyBreadcrumb},
  setup(props,{emit}) {
    const allDistrict = ref({})
    const unitFormRef = ref(null)
    const rankFormRef = ref(null)
    const xzRankDetailFormConfig = ref({...xzRankDetailForm})
    function saveInfo(){

      console.log('unitFormRef.value',unitFormRef.value,rankFormRef.value)

      const isVForm = [unitFormRef.value,rankFormRef.value].filter(i => Boolean(i))
       Promise.all(isVForm.map(i => i.refEl.validate(isValid => {
         Promise.resolve(isValid)
       }))).then(res =>{
         if (res.find(i => !Boolean(i)) === undefined){
           let params = {}
           let url = ''
           if (props.tabName === 'kj'){
             if (props.operationType ==='add'){
               params = {
                 a_name:form.value.NAME,
                 a_address:form.value.ADDRESS,
                 a_manager:form.value.MANAGER,
                 a_zipcode:form.value.ZIPCODE,
                 a_faxnum:form.value.FAXNUM,
                 a_telephone:form.value.TELEPHONE,
                 a_mail:form.value.MAIL,
                 a_is_superior:form.value.IS_SUPERIOR,
                 a_superior:form.value.SUPERIOR,
                 a_codes:form.value.industyCodeArr.join('-'),
                 appkey:useRootStore().userInfo.ptjk_userkeycode
               }
               url = addUnitInfoSpace
             }else {
               params = {
                 a_code:props.currentObObj.CODE,
                 a_name:form.value.NAME,
                 a_address:form.value.ADDRESS,
                 a_manager:form.value.MANAGER,
                 a_zipcode:form.value.ZIPCODE,
                 a_faxnum:form.value.FAXNUM,
                 a_telephone:form.value.TELEPHONE,
                 a_mail:form.value.MAIL,
                 a_is_superior:form.value.IS_SUPERIOR,
                 a_superior:form.value.SUPERIOR,
                 a_codes:form.value.industyCodeArr.join('-'),
                 appkey:useRootStore().userInfo.ptjk_userkeycode
               }
               url = editUnitInfoSpace
             }

           }
           else  if (props.tabName === 'zw'){
             if (props.operationType ==='add'){
               params = {
                 a_code:form.value.CODE,
                 a_name:form.value.NAME,
                 a_address:form.value.ADDRESS,
                 a_manager:form.value.MANAGER,
                 a_zipcode:form.value.ZIPCODE,
                 a_faxnum:form.value.FAXNUM,
                 a_telephone:form.value.TELEPHONE,
                 a_mail:form.value.MAIL,
                 a_is_superior:form.value.IS_SUPERIOR,
                 a_superior:form.value.SUPERIOR,
                 a_codes:form.value.industyCodeArr.join('-'),
                 appkey:useRootStore().userInfo.ptjk_userkeycode
               }
               url = addUnitInfoZw
             }else {
               params = {
                 a_code:props.currentObObj.CODE,
                 a_name:form.value.NAME,
                 a_address:form.value.ADDRESS,
                 a_manager:form.value.MANAGER,
                 a_zipcode:form.value.ZIPCODE,
                 a_faxnum:form.value.FAXNUM,
                 a_telephone:form.value.TELEPHONE,
                 a_mail:form.value.MAIL,
                 a_is_superior:form.value.IS_SUPERIOR,
                 a_superior:form.value.SUPERIOR,
                 a_codes:form.value.industyCodeArr.join('-'),
                 appkey:useRootStore().userInfo.ptjk_userkeycode,
                 a_UNIT_LEVEL:form.value.a_UNIT_LEVEL,
                 a_REGION_NAME:form.value.a_REGION_NAME,
                 a_STREET_TOWN:form.value.a_STREET_TOWN
               }
               url = editUnitInfoZw
             }

           }
           url(params).then(res => {
             handleMes(res,() => {
               emit('changeOperation','')
             })
           })
         }
      }).catch(err => {

       })


    }
    const isIndustaryDialogIsShow = ref(false)
    const form = ref({

    })
    function getDialogInfo(ck){
      isIndustaryDialogIsShow.value = false
      form.value.INDUSTRY = ck.map(i => i.NAME).join(',')
      form.value.industyCodeArr = ck.map(i => i.CODE)
    }
    // const currentObj =computed(() => {
    //   return staTabReflectArr.find(i=>i.id===route.name)
    // })
      const unitManageDetailFormConfig = ref({
        formItemsArr:[],
        formAttrs:{}
      })
    onMounted(() => {
      unitManageDetailFormConfig.value = {...(props.tabName === 'kj'?unitManageDetailForm:unitManageDetailFormZw)}
      console.log('saddas',props.tabName)
      const SUPERIORForm = unitManageDetailFormConfig.value.formItemsArr.find(i => i.modelValue === 'SUPERIOR')
      watch(() => +form.value.IS_SUPERIOR,(val) => {

        SUPERIORForm.isHide = !(+val === 0)

      },{
        immediate:true
      })
      // 设置所属行业的聚焦
       const findIndustry=  unitManageDetailFormConfig.value.formItemsArr.find(i => i.modelValue === 'INDUSTRY')

      findIndustry.events = {
        focus(e) {
          e.target.blur()
          isIndustaryDialogIsShow.value = true

        }
      }

      console.log('拿到二',props.tabName)
      let unitListUrl = props.tabName === 'kj'?getDetailUnitListSpace:getDetailUnitListZw
      console.log('appkey',useRootStore().userInfo.ptjk_userkeycode)
      unitListUrl({
        appkey:useRootStore().userInfo.ptjk_userkeycode
      }).then(res => {
        let data
        try {
          data = res.msg[0].Rows
        }catch {}
        SUPERIORForm.options = [{value:'',label:'请选择'}].concat(data.map(i => ({
          label:i.NAME,
          value:i.CODE,
        })))
      })
       if (props.operationType!=='add'){
         let url = props.tabName === 'kj'?getUnitManageDetailTableDataSpace:getUnitManageDetailTableDataZw
         url(props.currentObObj.CODE).then(res => {
           let data
           try {
             data = res.msg[0].Rows[0]
           }
           catch {

           }
           form.value = {
             ...form.value,
             ...data,
             INDUSTRY:form.value.INDUSTRY,

           }
         })
       }


      getUnitManageDetailAllIndustry({
        pageIndex:1,
        pageSize:20000,
        a_code:props.currentObObj.CODE || '',

      }).then(res => {
        let data
        try {
          data  = res.msg[0].Rows
        }catch {

        }

        form.value.INDUSTRY = data.filter(i => +i.SELECTED).map(i => i.NAME).join(',')
        form.value.industyCodeArr = data.filter(i => +i.SELECTED).map(i => i.CODE)
      })
      if (props.tabName === 'zw'){
        getZwUnitSpaceArea().then(res => {
          allDistrict.value = res.msg[0].Rows[0]
        })
        let findRank = xzRankDetailFormConfig.value.formItemsArr.find(i => i.modelValue === 'a_UNIT_LEVEL')
        let findArea = xzRankDetailFormConfig.value.formItemsArr.find(i => i.modelValue === 'a_REGION_NAME')
        let streetArea = xzRankDetailFormConfig.value.formItemsArr.find(i => i.modelValue === 'a_STREET_TOWN')
        findArea.events = {
          change(val){
             streetArea.options = [{value:'',label:'请选择街道'}].concat(allDistrict.value[val].map(i =>({
               label:i.TOWN,
               value:i.TOWN
             })))
             form.value['a_STREET_TOWN'] = ''

          }
        }
        findRank.events = {
          change(val){
            findArea.options = [{value:'',label:'请选择区域'}].concat(Object.keys(allDistrict.value).map(i =>({
              label:i,
              value:i
            })))
            form.value['a_REGION_NAME'] = ''
          }
        }
        let findCode = unitManageDetailFormConfig.value.formItemsArr.find(i => i.modelValue === 'CODE')
        findCode.elInputEleAttrs &&  (findCode.elInputEleAttrs.disabled = props.operationType !== 'add')
      //   区域联动
        watch(() => form.value.a_UNIT_LEVEL,(val) => {
          console.log('开始计划',val)
          let findArea = xzRankDetailFormConfig.value.formItemsArr.find(i => i.modelValue === 'a_REGION_NAME')
          let streetArea = xzRankDetailFormConfig.value.formItemsArr.find(i => i.modelValue === 'a_STREET_TOWN')

          if (!val || val === '市'){
            findArea.options = [{value:'',label:'请选择区域'}]
            streetArea.options = [{value:'',label:'请选择街道'}]
            findArea.itemOtherAttrs.required = streetArea.itemOtherAttrs.required = false
            findArea.isHide = streetArea.isHide = true
          }else if (val === '区'){
            findArea.options =  [{value:'',label:'请选择区域'}].concat(Object.keys(allDistrict.value).map(i =>({
              label:i,
              value:i
            })) || [])
            findArea.itemOtherAttrs.required = true
            findArea.isHide = false
            streetArea.options = [{value:'',label:'请选择街道'}]
            streetArea.itemOtherAttrs.required = false
            streetArea.isHide = true
          }else {
            findArea.options =  [{value:'',label:'请选择区域'}].concat(Object.keys(allDistrict.value).map(i =>({
              label:i,
              value:i
            })))

            findArea.itemOtherAttrs.required =  streetArea.itemOtherAttrs.required  = true
            findArea.isHide =  streetArea.isHide  = false
          }
        },{
          immediate:true
        })
        getZwUnitSetRegion(props.currentObObj.CODE).then(res => {
          form.value  ={
            ...form.value,
            a_UNIT_LEVEL:res.msg[0].Rows[0].UNIT_LEVEL,
            a_REGION_NAME:res.msg[0].Rows[0].REGION_NAME,
            a_STREET_TOWN:res.msg[0].Rows[0].STREET_TOWN,
            ...res.msg[0].Rows[0]
          }
        })
      }


    })
    const myBreadArr = [
      {name:'单位管理'},
      {name:'单位管理新增'},
    ]

    return {
      myBreadArr,
      form,
      unitManageDetailFormConfig,
      isIndustaryDialogIsShow,
      getDialogInfo,
      saveInfo,
      xzRankDetailFormConfig,
      allDistrict,
      unitFormRef,
      rankFormRef
    }
  }
}
</script>

<style scoped lang="scss">

</style>
