<template>
 <div class="rule position-re">
  <el-breadcrumb separator="/" class="my-breadcrumb">
    <el-breadcrumb-item>知识库</el-breadcrumb-item>
    <el-breadcrumb-item>质检规则</el-breadcrumb-item>
  </el-breadcrumb>
   <div class="back" @click="$emit('changeOperation','',{})"><span class="fa fa-reply cur-po " >返回</span></div>
   <div class="filter-form">
     <diy-el-form :span-attrs="{
     span:5
   }" :forms="qualityCheckDetailFilterFormConfig" v-model:model-form="forms">
       <template #searchBtn>
         <el-button type="primary" :icon="Search" @click="initSearch">查询</el-button>
       </template>
       <template #addBtn>
         <el-button type="primary" :icon="Plus" @click="openDialog('add',{})">新增</el-button>
       </template>
     </diy-el-form>
   </div>
   <div class="data-source-a">
     <span class="data-source">数据资源</span>
     <span class="total">共 <strong>{{totalCount}}</strong> 个规则项</span>

   </div>
   <div class="my-detail-main">
     <my-table
       border

       :table-data="tableData"

       :page-size="8"
       :has-operation="true"
       :headers="qualityCheckRuleRuleTableHeader"
     >
       <template #IS_RELATION="{data}">
         {{data['IS_RELATION'] === '0'?'否':(data['IS_RELATION'] === '1'?'是':'-')}}
       </template>
       <template #QUALITY_RULE="{data}">
         {{getPznr(data['QUALITY_RULE'],data)}}
       </template>
       <template #operation="{data}">
         <template v-if="data.STATE === '1'">
           <el-button type="danger"  size="small" @click="changeStatus(data)">禁用</el-button>
           <el-button type="primary" size="small" @click="openDialog('detail',data)">查看</el-button>
         </template>
         <template v-else>
           <el-button type="info"  size="small" @click="changeStatus(data)">启用</el-button>
           <el-button type="primary" size="small" @click="openDialog('edit',data)">编辑</el-button>
           <el-button type="primary" size="small" @click="delQualityCheckRule(data)">删除</el-button>
         </template>

       </template>
     </my-table>
     <ele-pagination  ref="refEl"


                      @sizeOrPageChange="handleSizeChange"
                      class="page"
                      :default-page-size="pageSize"


                      :total-count="totalCount">

       <template #default>
         <div class="m-s">
           显示第 {{pageSize * (pageIndex -1) + 1 }} 到第 {{pageSize * pageIndex}} 条记录，总共 {{totalCount}} 条记录 共显示

         </div>
       </template>
     </ele-pagination>
<!--     <div class="m-s">-->
<!--       显示第 {{1 }} 到第 {{totalCount}} 条记录，总共 {{totalCount}} 条记录-->

<!--     </div>-->
   </div>

   <template v-if="isEditDictionaryDialogShow">
     <quality-check-seting-dialog
       @changeOrAddDataD="changeOrAddDataD"
       :all-dictionary-arr="allDictionaryArr"
       :current-dialog-obj="currentDialogObj"

       :current-op-obj="currentOpObj" :dialog-operation-type="dialogOperationType" :rule-arr="ruleArr" :filed-arr="filedArr" v-model:dialog-visible="isEditDictionaryDialogShow"/>
   </template>
 </div>


</template>

<script>
import DiyElForm from "@/components/common/DiyElForm.vue";
import {onBeforeMount, ref} from "vue";
import { qualityCheckDetailFilterForm, syncDetailFilterForm} from "@/data/all-forms";
import {DocumentAdd, Plus, Search} from "@element-plus/icons-vue";
import MyTable from "@/components/common/MyTable.vue";
import {useClickRouterToHome, usePagination} from "@/unit/use-method/usePagination";
import ElePagination from "@/components/common/ElePagination.vue";
import {

  qualityCheckRuleRuleTableHeader
} from "@/data/all-table-header";

import SyncRuleSetingDialog from "@/view/other/c-views/data-handle/zsk/sync-rule/SyncRuleSetingDialog.vue";
import QualityCheckSetingDialog from "@/view/other/c-views/data-handle/zsk/quality-check-rule/QualityCheckSetingDialog.vue";
import {
  addOrEditQualityRule,
  deleteQualityCheck,
  getQualityDetailRuleAllFieldSelect,
  getQualityDetailRuleSelect,
  qualityCheckRuleDetailTableData, validDataDictionary
} from "@/service/zsk/quality-check-rule";
import {useRootStore} from "@/stores/useStore";
import {isEmptyCheck} from "@/unit/validate";
import {elAlert, handleMes, showConfirm} from "@/unit/element-ui/tip";
import {addQualityRuleD} from "@/service/zsk/base-rule/quality-rule";

export default {
  name: "QualityCheckRuleEdit",
  computed: {
    Plus() {
      return Plus
    },
    DocumentAdd() {
      return DocumentAdd
    },
    Search() {
      return Search
    }
  },
  components: {
    QualityCheckSetingDialog,
    SyncRuleSetingDialog, ElePagination, MyTable, DiyElForm},
  props:{
    currentOpObj:{

    },

  },
  setup(props) {
   function openEditOrAddDialog() {
     isEditDictionaryDialogShow.value = true

   }
   function changeOrAddDataD(forms,re,quality) {
     let params = {
       STATE:currentDialogObj.value.STATE || '2',
       CATALOG_CODE:props.currentOpObj.CODE,
       TYPE_CODE:forms.rule,
       FIELD_NAME:(forms.field || []).join(','),
       IS_RELATION:re.length >0?'1':'0',
       ERROR_MSG:forms.ERROR_MSG,
       UUID:currentDialogObj.value.UUID || '',
       QUALITY_RULE:quality,
       RELATION_FIELD:re
     }
     addOrEditQualityRule(params).then(res => {
       handleMes(res,()=>{
         isEditDictionaryDialogShow.value = false
         getTableList()
       })
     })
     console.log('所有params',params)
   }
   const allDictionaryArr = ref([])
   const {currentOpObj:currentDialogObj,operationType:dialogOperationType,changeOperation:changeDialogOperation} = useClickRouterToHome()
    const isEditDictionaryDialogShow =  ref(false)
    const store  =useRootStore()
    const filedArr = ref([])
    const ruleArr = ref([])
    function getTableList() {
      qualityCheckRuleDetailTableData({
        pageIndex:pageIndex.value,
        pageSize:pageSize.value,
        CODE:props.currentOpObj.CODE,
        FIELD_NAME:forms.value.FIELD_NAME,
        TYPE_CODE:forms.value.TYPE_CODE === 'GLGZ'?'':forms.value.TYPE_CODE,
        STATE:forms.value.STATE,
        IS_RELATION:forms.value.TYPE_CODE === 'GLGZ'?'1':''

      }).then(res => {
        tableData.value = res.msg[0].Rows || []
        totalCount.value =res.msg[0].TotalRowCount
      })

    }


    function changeStatus(data) {


      addQualityRuleD({
        CATALOG_CODE:data.CATALOG_CODE,
        TYPE_CODE:data.TYPE_CODE,
        FIELD_NAME:data.FIELD_NAME,
        IS_RELATION:data.IS_RELATION,
        QUALITY_RULE:data.QUALITY_RULE,
        ERROR_MSG:data.ERROR_MSG,
        UUID:data.UUID ||'',
        RELATION_FIELD:data.RELATION_FIELD,
        STATE:data.STATE === '1'?'2':'1',
      }).then(res => {
        handleMes(res,() =>{
          getTableList()
        },()=>{})
      })
    }
    function getConfigName(type, pcode) {
      let  json_configs
      //json_configs
      if (json_configs == null) {
        let para_configs = store.paraArr
        for (var i = 0 ; i < para_configs.length ; i++) {
          if (json_configs == null || isEmptyCheck(json_configs[para_configs[i]["PARA_CODE"]])) {
            if (json_configs == null) {
              json_configs = {};
            }
            var code = para_configs[i]["CODE"];
            var name = para_configs[i]["NAME"];
            json_configs[para_configs[i]["PARA_CODE"]] = {};
            json_configs[para_configs[i]["PARA_CODE"]][code] = name;
          } else {
            var code = para_configs[i]["CODE"];
            var name = para_configs[i]["NAME"];
            json_configs[para_configs[i]["PARA_CODE"]][code] = name;
          }
        }
      }
      return json_configs[type][pcode] == null || json_configs[type][pcode] == "" ? pcode : json_configs[type][pcode];
    }
    // 配置内容
    function getPznr(value,row) {

      if (value != '[]' && value != '' && value != undefined) {
        var rule_value = JSON.parse(value);
        var rule_string = '';
        switch (row.CODE) {
          case "C0001":
            rule_string = '是否非空：'
            rule_string += rule_value[0].NOT_NULL == '1' ? '是' : '否';
            return rule_string;
          case "C0002":

            rule_string = getConfigName('90', rule_value[0].CHACK_TYPE) + ":" + rule_value[0].CHACK_VALUE + ";";
            return rule_string;
          case "C0003":
            rule_string = '是否唯一：'
            rule_string += rule_value[0].ONLY == '1' ? '是' : '否';
            return rule_string;
          case "C0004":
            getConfigName('92', rule_value[0].DATA_FORMAT);;
            rule_string += getConfigName('92', rule_value[0].DATA_FORMAT) + ";";
            return rule_string;
          case "C0005":
            getConfigName('90', rule_value[0].CHACK_TYPE);
            getConfigName('91', rule_value[0].DATA_TYPE);;
            rule_string += getConfigName('91', rule_value[0].DATA_TYPE) + ":" + getConfigName('90', rule_value[0].CHACK_TYPE) + ":" + rule_value[0].VALUE + ";";
            return rule_string;
          case "C0006":

            return rule_string;
          case "C0007":
            for (var i = 0; i < rule_value.length; i++) {
              rule_string +=  rule_value[i].VALUE + ";";
            }
            return rule_string;
          case "C0009":
            rule_string = '数据字典'
            return rule_string;
          case "C0010":
            rule_string = '文件验证';
            return rule_string;
          case "C0011":
            rule_string = '截取验证';
            return rule_string;
          case "C0013":
            rule_string = '判断节点是否合法';
            return rule_string;
        }
      }
    }
    const {pageIndex,pageSize,tableData,totalCount,handleSizeChange,refEl,initSearch}  = usePagination(getTableList.bind(null))
    const qualityCheckDetailFilterFormConfig = ref({...qualityCheckDetailFilterForm})
    const forms = ref({

    })
    function delQualityCheckRule(data){
      showConfirm(() => {
        deleteQualityCheck(data.UUID).then(res => {
          handleMes(res,() => {
            getTableList()
          })
        })
      },'确定要删除吗','系统提示',{
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
    }
    onBeforeMount(() => {
      validDataDictionary(props.currentOpObj.CODE).then(res => {
        allDictionaryArr.value = res.msg[0].Rows || []
      })
      getQualityDetailRuleSelect().then(res => {
        let findGz = qualityCheckDetailFilterFormConfig.value.formItemsArr.find(i => i.modelValue === 'TYPE_CODE')
        findGz.options = [
          {
            value:'',
            label:'请选择'
          },  {
            value:'GLGZ',
            label:'关联规则'
          }

        ].concat(res.msg[0].Rows.map(i => ({

          value:i.CODE,
          label:i.NAME
        })))
        ruleArr.value = findGz.options = [
          {
            value:'',
            label:'请选择'
          }

        ].concat(res.msg[0].Rows.map(i => ({

          value:i.CODE,
          label:i.NAME
        })))
      })
      getQualityDetailRuleAllFieldSelect(props.currentOpObj.CODE).then(res => {
        let findFiledName = qualityCheckDetailFilterFormConfig.value.formItemsArr.find(i => i.modelValue === 'FIELD_NAME')
        filedArr.value=   findFiledName.options = [
          {
            value:'',
            label:'请选择'
          }

        ].concat(res.msg[0].Rows.map(i => ({
          ...i,
          value:i.INFOITEMENGLISHNAME,
          label:i.INFOITEMENGLISHNAME
        })))
      })
    })
    function openDialog(operationT,item){
      isEditDictionaryDialogShow.value = true
      changeDialogOperation(operationT,item)
    }
    return {
      forms,
      qualityCheckDetailFilterFormConfig,
      pageIndex,pageSize,tableData,totalCount,handleSizeChange,refEl,getTableList,
      qualityCheckRuleRuleTableHeader,
      isEditDictionaryDialogShow,
      openDialog,
      getPznr,
      delQualityCheckRule,
      syncDetailFilterForm,
      filedArr,
      ruleArr,
      currentDialogObj,

      dialogOperationType,
      changeStatus,
      allDictionaryArr,
      changeOrAddDataD,
      changeDialogOperation,
      initSearch
    }
  }
}
</script>

<style scoped lang="scss">
.filter-form{
  margin-top: 20px;
  border-bottom: 1px solid #e7eaec !important;
}
.my-breadcrumb{
  padding: 20px 20px 20px 20px;
  border-bottom: 1px solid #e7eaec !important;
}
.data-source-a{
  margin: 20px 0;
}
.data-source{

  margin-right: 10px;
  color: rgb(103, 106, 108);
  font-size: 16px;
  font-weight: 600;
}
.total{
  strong{
    color: rgb(55, 99, 156);
    font-weight: 700;
  }
  color: rgb(103, 106, 108);
  font-size: 13px;
}
.data-source-a,.filter-form{
  margin-left: 20px;
  margin-right: 20px;
}

</style>
