<template>
<el-dialog

  :modal="true"
   class="scroll-dialog"
  :close-on-click-modal="false"
  :close-on-press-escape="false"
  destroy-on-close
  title="配置规则"
  :model-value="dialogVisible"

  :before-close="handleClose"

>
  <el-tabs v-model="activeTab" type="card">
    <el-tab-pane label="配置" name="set">
      <div class=""    element-loading-text="加载中">
        <diy-el-form ref="form1Ref" class="form" :forms="asyncRuleDialogForm1Config" v-model:model-form="form"/>
        <div class="my-block">
          <div class="b-title">配置源信息</div>
          <diy-el-form ref="form2Ref" class="form" :forms="asyncRuleDialogForm2Config" v-model:model-form="form"/>
        </div>
        <div class="my-block">
          <div class="b-title">配置目标库信息</div>
          <diy-el-form ref="form3Ref" class="form" :forms="asyncRuleDialogForm3Config" v-model:model-form="form"/>
        </div>
        <div class="my-block">
          <div class="b-title">查询字段列表</div>
          <div class="add-div"><el-button type="info"  :icon="Plus"  @click="addTd(syncRuleDialogTableHeader1,'set')">新增</el-button></div>
          <my-table
            :has-operation="true"
            border

            :headers="syncRuleDialogTableHeader1"
            :table-data="setTableData"
          >
            <template #operation="{data,index}">
              <el-button circle :icon="Edit" @click="changeIsEdit(data)"></el-button>
              <el-button circle :icon="Delete" @click="delTableI(index)"></el-button>
            </template>
            <template #[item.prop]="{data}" v-for="item in syncRuleDialogTableHeader1.filter(i => i.prop!=='operation')">

              <el-input v-if="data.isEdit" v-model="data[item.prop]"/>
              <span v-else>{{data[item.prop]}}</span>
            </template>
          </my-table>
        </div>

      </div>
    </el-tab-pane>
    <el-tab-pane label="查看映射" name="ys">
      <div class="add-div"><el-button type="primary"  :icon="Plus" @click="addTd(syncRuleDialogTableHeader)">新增</el-button></div>
      <my-table
        :has-operation="true"
        border

        :headers="syncRuleDialogTableHeader"
        :table-data="tableData"
      >
         <template #operation="{data,index}">
           <el-button circle :icon="Edit" @click="changeIsEdit(data)"></el-button>
           <el-button circle :icon="Delete"  @click="delTableI2(index)"></el-button>
         </template>
        <template #[item.prop]="{data}" v-for="item in syncRuleDialogTableHeader.filter(i => i.prop!=='operation')">
          <el-input v-if="data.isEdit" v-model="data[item.prop]"/>
          <span v-else>{{data[item.prop]}}</span>
        </template>
      </my-table>
    </el-tab-pane>
  </el-tabs>



  <template #footer v-if="operationType !== 'detail'">
    <el-button :icon="SuccessFilled" @click="validateConfirm">确定</el-button>
    <el-button @click="handleClose" :icon="Close">取消</el-button>
  </template>
</el-dialog>
</template>

<script>
import {Close, Delete, Edit, Plus, SuccessFilled} from "@element-plus/icons-vue";
import DiyElForm from "@/components/common/DiyElForm.vue";
import {computed, onBeforeMount, ref, watch} from "vue";
import {
  asyncRuleDialogForm1,
  asyncRuleDialogForm2,
  asyncRuleDialogForm3,
  editDataDictionaryDialogForm
} from "@/data/all-forms";
import MyTable from "@/components/common/MyTable.vue";
import {usePagination} from "@/unit/use-method/usePagination";

import {
  editDataDictionaryDialogTableHeader,
  syncRuleDialogTableHeader,
  syncRuleDialogTableHeader1
} from "@/data/all-table-header";
import {
  addSyncRule,
  editSyncRule,
  getAllCircleAndModeSelect,
  getAllServiceAndTdSelect,
  getReflectTableData, getSheetAndTableAndSpace
} from "@/service/zsk/sync-rule";
import {serviceTypeArr} from "@/data/all-reflect";
import {isValid} from "js-base64";
import {elAlert, handleMes} from "@/unit/element-ui/tip";
import {getQualityDetailRuleAllFieldSelect} from "@/service/zsk/quality-check-rule";

export default {
  name: "SyncRuleSetingDialog",
  components: { MyTable, DiyElForm},
  computed: {
    Delete() {
      return Delete
    },
    Edit() {
      return Edit
    },
    Plus() {
      return Plus
    },
    SuccessFilled() {
      return SuccessFilled
    },
    Close() {
      return Close
    }
  },
  props:{
    dialogVisible:{

    },
    currentOpObj:{

    },
    currentDialogObj:{

    },
    operationType:{}
  },
  setup(props,{emit}){
    const setTableData = ref([])
    function addTd(header,type) {
      let obj = {}
      header.filter(i => i.prop!=='operation').forEach(i => {
        obj[i.prop] = ''
        obj.isEdit = true
      })
      if (type  ==='set'){
        setTableData.value.push(obj)
      }else {
        tableData.value.push(obj)
      }


    }
    const loading = ref(false)
    const activeTab = ref('set')
    const tableData = ref([])
    const form1Ref = ref(null)
    const form2Ref = ref(null)
    const form3Ref = ref(null)
    function changeIsEdit(item) {
      item.isEdit = !item.isEdit
    }
    function delTableI(index){
      setTableData.value.splice(index,1)
    }
    function delTableI2(index){
      tableData.value.splice(index,1)
    }
    function validateConfirm() {
      console.log('进屋了')
      form1Ref.value.refEl.validate(isValid => {
        if (isValid) {
          console.log('有效的')
          form2Ref.value.refEl.validate(isValid2 => {
            console.log('isValid2',isValid2)
            if (isValid2) {
              console.log('有效的2')
              form3Ref.value.refEl.validate((isValid3) => {
                if (isValid3){
                //   验证表格
                  let findNoColumn = setTableData.value.find(i => !i.COLUMN_NAME)
                  if (findNoColumn) {
                    elAlert('字段名称不能为空')
                  }else if (tableData.value.find(i => !i.SOURCE_NAME || !i.TARGET_NAME)){
                    elAlert('源字段和目录字段名称不能为空')
                  }else {
                    console.log('掉了接口')
                    addOrEditRule()
                  }

                }
              })
            }
          })
        }
      })
    }
    function addOrEditRule() {

      let params = {

        KETTLE_MODE:form.value.KETTLE_MODE,
        SEGMENT_ID:form.value.SEGMENT_ID,
        CATALOG_CID:props.currentOpObj.CATALOG_CODE,
        BUSINESSFIELDNAME:form.value.BUSINESSFIELDNAME,
        BUSINESSMAINKEY:form.value.BUSINESSMAINKEY,
        PARAMETERDEFINATIONNAME:form.value.PARAMETERDEFINATIONNAME,
        FIELDSTREAMSELECT:setTableData.value.map(i => i.COLUMN_NAME).join('，'),
        ORIGION_SERVER_NAME:form.value.service,
        ORIGION_TYPE:form.value.td,
        ORIGION_SPACE:form.value.ORIGION_SPACE,
        ORIGION_TABLENAME:form.value.ORIGION_TABLENAME,
        ORIGION_TABLEPARAMS:tableData.value.map(i => i.SOURCE_NAME).join('，'),
        TARGET_SERVER_NAME:form.value.targetService,
        TARGET_TYPE:form.value.targetTd,
        TARGET_SPACE:form.value.TARGET_SPACE,
        SOURCE_MAIN_KEY:form.value.SOURCE_MAIN_KEY.join('，'),
        TARGET_TABLENAME:form.value.TARGET_TABLENAME,
        TARGET_TABLEPARAMS:tableData.value.map(i => i.TARGET_NAME).join('，'),
        KETTLE_RULE_STATES:props.operationType === 'add'?'2':props.currentDialogObj.KETTLE_RULE_STATES
      }
      if (props.operationType !== 'add'){
        params.KETTLE_RULE_ID=props.currentDialogObj.KETTLE_RULE_ID
        editSyncRule(params).then(res => {
          handleMes(res,() => {
            emit('addOrEditRule')
          })
        })
      }else {
        addSyncRule(params).then(res => {
          handleMes(res,() => {
            emit('addOrEditRule')
          })
        })
      }
    }
    const serviceTdArr = ref([])
    const asyncRuleDialogForm1Config = ref({...asyncRuleDialogForm1})
    const asyncRuleDialogForm2Config = ref({...asyncRuleDialogForm2})
    const asyncRuleDialogForm3Config = ref({...asyncRuleDialogForm3})
    const form= ref({

    })
    const sourceServiceAndTd = computed(() => {
      return {
        service:form.value.service,
        td:form.value.td,
      }
    })
    const targetServiceAndTd = computed(() => {
      return {
        service:form.value.targetService,
        td:form.value.targetTd,
      }
    })
    onBeforeMount(() => {
      const findTd = asyncRuleDialogForm2Config.value.formItemsArr.find(i => i.modelValue === 'service')
      const findTd2 = asyncRuleDialogForm2Config.value.formItemsArr.find(i => i.modelValue === 'td')
      findTd.events = {
        change(val){
          form.value['td'] = ''
          form.value['ORIGION_SPACE'] = form.value['ORIGION_TABLENAME'] = ''

        }
      }
      findTd2.events = {
        change(val){

          form.value['ORIGION_SPACE'] = form.value['ORIGION_TABLENAME'] = ''

        }
      }
      const findTTd = asyncRuleDialogForm3Config.value.formItemsArr.find(i => i.modelValue === 'targetService')
      const findTTd2 = asyncRuleDialogForm3Config.value.formItemsArr.find(i => i.modelValue === 'targetTd')

      findTTd.events = {
        change(val){
          form.value['targetTd'] = ''
          form.value['TARGET_TABLENAME'] = form.value['TARGET_SPACE'] = ''
        }
      }
      findTTd2.events = {
        change(val){

          form.value['TARGET_TABLENAME'] = form.value['TARGET_SPACE'] = ''
        }
      }
      asyncRuleDialogForm1Config.value.formAttrs.disabled=props.operationType === 'detail'
      asyncRuleDialogForm2Config.value.formAttrs.disabled=props.operationType === 'detail'
      asyncRuleDialogForm3Config.value.formAttrs.disabled=props.operationType === 'detail'
      getAllCircleAndModeSelect().then(res => {
          const findHj = asyncRuleDialogForm1Config.value.formItemsArr.find(i => i.modelValue === 'SEGMENT_ID')
          const findMode = asyncRuleDialogForm1Config.value.formItemsArr.find(i => i.modelValue === 'KETTLE_MODE')
          let data = res.msg[0].Rows || []
          data.forEach(i => {
            let modeObj = {
              value:i.ORIGION_DETAIL_CODE,
              label:i.ORIGION_DETAIL_TYPE
            }
            let hjObj = {
              value:i.ORIGION_MODE_CODE,
              label:i.ORIGION_MODE
            }
            let findHjHas = findHj.options.find(it => it.value === i.ORIGION_MODE_CODE)
            let  findModeHas = findMode.options.find(it => it.value === i.ORIGION_DETAIL_CODE)
            if (!findHjHas) {
              findHj.options.push(hjObj)
            }
            if (!findModeHas) {
              findMode.options.push(modeObj)
            }
          })
      })
      function getTdOptions() {
        const findTdEqual = asyncRuleDialogForm2Config.value.formItemsArr.find(i => i.modelValue === 'td')
        const isEq = serviceTdArr.value.filter(i => i.DATASOURCE_ID === form.value.service)
        let optionArr = [ ]
        isEq.forEach(i => {

          switch (i.DATASOURCE_UNIT_TYPE){
            case "0":
              optionArr.push({value:i.DATASOURCE_UNIT_TYPE,label:'ORACLE'})
            break
            case "1":
              optionArr.push({value:i.DATASOURCE_UNIT_TYPE,label:'SQLSERVER'})
              break
            case "2":
              optionArr.push({value:i.DATASOURCE_UNIT_TYPE,label:'MYSQL'})
              break
            case "3":
              optionArr.push({value:i.DATASOURCE_UNIT_TYPE,label:'接口'})
              break
            case "4":
              optionArr.push({value:i.DATASOURCE_UNIT_TYPE,label:'FTP'})
              break
            case "5":
              optionArr.push({value:i.DATASOURCE_UNIT_TYPE,label:'DM'})
              break
            case "6":
              optionArr.push({value:i.DATASOURCE_UNIT_TYPE,label:'KINGBASE'})
              break
          }
        })
        findTdEqual.options= [{value:'',label:'请选择'},...optionArr]
        console.log('是否想等',form.value.service,isEq,serviceTdArr.value)
      }

      watch(() => sourceServiceAndTd.value,(val) => {
        const findBqK = asyncRuleDialogForm2Config.value.formItemsArr.find(i => i.modelValue === 'ORIGION_SPACE')
        const findBqT = asyncRuleDialogForm2Config.value.formItemsArr.find(i => i.modelValue === 'ORIGION_TABLENAME')
        if (val.service && val.td){
          if (loading.value){
            loading.value = false
          }
          loading.value = true
          getSheetAndTableAndSpace({
            "DATA_SOURCE_UUID":val.service,
            "BUSINESS_TYPE":"2",
            "DATABASE_TYPE":val.td //通道
          }).then(res => {
            loading.value = false
            let data = []
            try{
               data = res.msg[0].Rows || []
            }catch {
              data = []

            }
            finally {

              let arr = data.map(i => {
                return (i || '').split('.')[0]
              })
              findBqK.options = Array.from(new Set(arr)).map(i => {
                return {
                  value:i,
                  label:i
                }
              })
              let arr2 = data.map(i => {
                return (i || '').split('.')[1]
              })
              findBqT.options = Array.from(new Set(arr2)).map(i => {
                return {
                  value:i,
                  label:i,
                }
              })
            }

          })
        }else {

          findBqK.options  = findBqT.options = [
            {value:'',label:'请选择'}
          ]
        }
      },{

        deep:true
      })
      watch(() => targetServiceAndTd.value,(val) => {
        const findBqK = asyncRuleDialogForm3Config.value.formItemsArr.find(i => i.modelValue === 'TARGET_SPACE')
        const findBqT = asyncRuleDialogForm3Config.value.formItemsArr.find(i => i.modelValue === 'TARGET_TABLENAME')
        if (val.service && val.td){
          if (loading.value){
            loading.value = false
          }
          loading.value = true
          getSheetAndTableAndSpace({
            "DATA_SOURCE_UUID":val.service,
            "BUSINESS_TYPE":"2",
            "DATABASE_TYPE":val.td //通道
          }).then(res => {
            loading.value = false
            let data = []
            try{
              data = res.msg[0].Rows || []
            }catch {
              data = []

            }
            finally {
              let arr = data.map(i => {
                return (i || '').split('.')[0]
              })
              findBqK.options = Array.from(new Set(arr)).map(i => {
                return {
                  value:i,
                  label:i
                }
              })
              let arr2 = data.map(it => {
                return (it || '').split('.')[1]
              })
              findBqT.options =   Array.from(new Set(arr2)).map(i => {
                return {
                  value:i,
                  label:i,
                }
              })
            }

          })
        }else {

          findBqK.options  = findBqT.options = [
            {value:'',label:'请选择'}
          ]
        }
      },{

        deep:true
      })
      function getTargetTdOptions() {
        const findTdEqual = asyncRuleDialogForm3Config.value.formItemsArr.find(i => i.modelValue === 'targetTd')
        const isEq = serviceTdArr.value.filter(i => i.DATASOURCE_ID === form.value.targetService)
        let optionArr = [ ]
        isEq.forEach(i => {

          switch (i.DATASOURCE_UNIT_TYPE){
            case "0":
              optionArr.push({value:i.DATASOURCE_UNIT_TYPE,label:'ORACLE'})
            break
            case "1":
              optionArr.push({value:i.DATASOURCE_UNIT_TYPE,label:'SQLSERVER'})
              break
            case "2":
              optionArr.push({value:i.DATASOURCE_UNIT_TYPE,label:'MYSQL'})
              break
            case "3":
              optionArr.push({value:i.DATASOURCE_UNIT_TYPE,label:'接口'})
              break
            case "4":
              optionArr.push({value:i.DATASOURCE_UNIT_TYPE,label:'FTP'})
              break
            case "5":
              optionArr.push({value:i.DATASOURCE_UNIT_TYPE,label:'DM'})
              break
            case "6":
              optionArr.push({value:i.DATASOURCE_UNIT_TYPE,label:'KINGBASE'})
              break
          }
        })
        findTdEqual.options= [{value:'',label:'请选择'},...optionArr]
        console.log('是否想等',form.value.service,isEq,serviceTdArr.value)
      }
      watch(() =>form.value.service,(val) => {
        getTdOptions()

      })
      watch(() =>form.value.targetService,(val) => {
        getTargetTdOptions()

      })
      getAllServiceAndTdSelect().then(res => {

        const findService = asyncRuleDialogForm2Config.value.formItemsArr.find(i => i.modelValue === 'service')
        const findTd = asyncRuleDialogForm2Config.value.formItemsArr.find(i => i.modelValue === 'td')
        const targetFindTd = asyncRuleDialogForm3Config.value.formItemsArr.find(i => i.modelValue === 'targetTd')
        const targetService = asyncRuleDialogForm3Config.value.formItemsArr.find(i => i.modelValue === 'targetService')
        let data = res.msg[0].Rows || []
        serviceTdArr.value = data
        data.forEach(i => {
          let serviceObj = {
            value:i.DATASOURCE_ID,
            label:i.DATASOURCE_NAME
          }
          // let tdObj = {
          //   value:i.DATASOURCE_UNIT_TYPE,
          //   label:serviceTypeArr.find(it => it.type === i.DATASOURCE_UNIT_TYPE)?.label
          // }
          let findServiceHas = findService.options.find(it => it.value === i.DATASOURCE_ID)
          // let findTdHas = findTd.options.find(it => it.value === i.DATASOURCE_UNIT_TYPE)
          if (!findServiceHas) {
            findService.options.push(serviceObj)
          }
          // if (!findTdHas) {
          //   findTd.options.push(tdObj)
          // }
        })
        targetFindTd.options = findTd.options
        targetService.options = findService.options
        if (props.operationType !=='add'){
          form.value = {
            ...props.currentDialogObj,
            service:props.currentDialogObj.ORIGION_SERVER_NAME,
            targetService:props.currentDialogObj.TARGET_SERVER_NAME,
            td:props.currentDialogObj.ORIGION_TYPE,
            targetTd:props.currentDialogObj.TARGET_TYPE,
            // BUSINESSMAINKEY:props.currentDialogObj.BUSINESSMAINKEY?.replaceAll(',','，').split('，')
            SOURCE_MAIN_KEY:props.currentDialogObj.SOURCE_MAIN_KEY?.split('，')
          }
        }
        getTdOptions()
        getTargetTdOptions()
      })

    //   获取映射的表格
      getReflectTableData(props.currentOpObj.CATALOG_CODE).then(res => {
        // 源表空间
        let findSourceKey = asyncRuleDialogForm2Config.value.formItemsArr.find(i => i.modelValue === 'SOURCE_MAIN_KEY')

        if (props.operationType === 'add'){
          // ORIGION_TABLEPARAMS
          tableData.value = res.msg[0].Rows.map(i => ({
            ...i,
            SOURCE_NAME:i.YSGX.split('-->')[0],
            TARGET_NAME:i.YSGX.split('-->')[1],
            isEdit:false,

          }))
          form.value = {
            BUSINESSFIELDNAME:'MARK_BUSINESS_TIME',
            // ORIGION_TABLENAME:tableData.value[0]?tableData.value[0].TABNAME:'',
            // TARGET_TABLENAME:tableData.value[0]?tableData.value[0].TABNAME:'',
          }
          setTableData.value = res.msg[0].Rows.map(i => ({
            ...i,
            COLUMN_NAME:i.YSGX.split('-->')[0],
            isEdit:false,

          }))
        }else {
        // .replaceAll(',','，')
          console.log(' (props.currentDialogObj.FIELDSTREAMSELECT || \'\').split(\',\')', (props.currentDialogObj.FIELDSTREAMSELECT || '').split(','))
          // setTableData.value = (props.currentDialogObj.FIELDSTREAMSELECT || '').replaceAll(',','，').split('，').map(i => ({
          setTableData.value = (props.currentDialogObj.FIELDSTREAMSELECT || '').split('，').map(i => ({
            COLUMN_NAME:i
          }))
          // tableData.value = (props.currentDialogObj.ORIGION_TABLEPARAMS || '').replaceAll(',','，').split('，').map((i,index) => {
          tableData.value = (props.currentDialogObj.ORIGION_TABLEPARAMS || '').split('，').map((i,index) => {
            return {
              SOURCE_NAME:i,
              TARGET_NAME:props.currentDialogObj.TARGET_TABLEPARAMS.split('，')[index],
            }
          })
        }
        findSourceKey.options = [{
          value:'MARK_UUID',
          label:'MARK_UUID',
        }].concat(setTableData.value.map(it => ({
          value:it.COLUMN_NAME,
          label:it.COLUMN_NAME,
        })))
        // let findSourceKey = asyncRuleDialogForm2Config.value.formItemsArr.find(i => i.modelValue === 'BUSINESSMAINKEY')
        // findSourceKey.options = [{
        //   value:'MARK_UUID',
        //   label:'MARK_UUID',
        // }].concat(tableData.value.map(it => ({
        //   value:it.COLUMN_NAME,
        //   label:it.COLUMN_NAME,
        // })))
      })


      // findSourceKey.options = tableData.value.map()
    })
   function handleClose() {
      emit('update:dialogVisible',false)
    }
    return {
     handleClose,
      form,
      editDataDictionaryDialogForm,
     tableData,
      syncRuleDialogTableHeader,
      activeTab,
      changeIsEdit,
      asyncRuleDialogForm1Config,
      asyncRuleDialogForm2Config,
      asyncRuleDialogForm3Config,
      syncRuleDialogTableHeader1,
      form1Ref,form2Ref,form3Ref,
      validateConfirm,
      addTd,
      setTableData,
      loading,
      delTableI,
      delTableI2
    }
  }
}
</script>

<style scoped lang="scss">
.my-block{
  .b-title{
    margin-bottom: 20px;
    font-size: 14px;
    font-weight: 600;
    line-height: 40px;
    color: #676a6c;
    border-bottom: 1px solid var(--el-border-color-light);
  }
}
.form{
  padding-left: 10%;
  padding-right: 10%;
}
.set-content{
  margin-top: 10px;

}
.add-div{
  margin-bottom: 10px;
  text-align: right;
}
:deep{
  .el-tab-pane[aria-hidden="true"]{
     display: block !important;
    height: 0;
    overflow: hidden;
  }
}
</style>
