<template>
  <div class="settingForm">
    <baseNewForm
        ref="typeOptionForm"
        :spanNumber="18"
        :isFunBtn="false"
        :formRow="formRow"
        :ruleForm="ruleForm"
        :labelPosition="'top'"
        @onSelect="typeSelectChangeHanlde"
        @onSubmit="typeOptionOnSubmit"
    >
    </baseNewForm>
    <div class="bigTitle">数据权限设置</div>
    <div class="tableName">
      <div class="title">数据主表名称</div>
      <div class="input">
        <el-select clearable v-model="tableId" @change="serviceSeleChangHadle">
          <el-option v-for="(item,index) of serviceOptions" :key="index" :label="item.label"
                     :value="item.id"
          >
          </el-option>
        </el-select>
      </div>
    </div>
    <div class="main" v-loading="mainLoading">
      <!--      此处逻辑当拥有左括号或者右括号时 连接符清除并禁用-->
      <baseTable :tableData="tableData" :tabLoading="tabLoading"
                 :tableColumn="tableColumn" :border="false"
      >
        <!--        左括号-->
        <template #leftBracket="{row}">
          <el-select clearable v-model="row.leftBracket"
          >
            <el-option v-for="(item,index) of leftBracketOptions" :key="index" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </template>
        <!--        字段名称-->
        <template #filedName="{row}">
          <el-select clearable v-model="row.filedId" @change="(val)=>{filedIdChangHandle(val,row)}">
            <el-option v-for="(item,index) of labelOptions" :key="index" :label="item.label" :value="item.id">
            </el-option>
          </el-select>
        </template>
        <!--        对比类型-->
        <template #compareType="{row}">
          <el-select clearable v-model="row.compareType">
            <el-option v-for="(item,index) of compareTypeOptions" :key="index" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </template>
        <!--        运算值-->
        <template #filedVaule="{row}">
          <el-input v-model="row.filedVaule"></el-input>
        </template>
        <!--        连接符-->
        <template #connectionSymbol="{row}">
          <el-select clearable v-model="row.connectionSymbol"
          >
            <el-option v-for="(item,index) of connectionSymbolOptions" :key="index" :label="item.label"
                       :value="item.value"
            >
            </el-option>
          </el-select>
        </template>
        <!--        右括号-->
        <template #rightParenthesis="{row}">
          <el-select clearable v-model="row.rightParenthesis">
            <el-option v-for="(item,index) of rightParenthesisOptions" :key="index" :label="item.label"
                       :value="item.value"
            >
            </el-option>
          </el-select>
        </template>
        <!--        操作-->
        <template #operation="{row}">
          <div class="btnList">
            <div class="deleBtn" @click="activedOnFunc(row)">
              <img src="./images/删除.png" alt="">
            </div>
          </div>
        </template>
      </baseTable>
      <div class="receiptsAddRow">
        <el-link
            type="primary"
            @click="addRowHandle"
            :underline="false"
        >+ 添加
        </el-link
        >
      </div>
    </div>
  </div>
</template>
<script>
import baseNewForm from '../compoments/baseNewForm'
import BaseTable from '@/views/intergrationTask/compoments/baseTable.vue'
import { authApi } from '@/api/apis/auth'
import { getApiModuleApi } from '@/api/apiChunks'
import { retrieveRawAttr } from 'echarts/lib/data/helper/dataProvider'

export default {
  name: 'settingForm',
  data() {
    return {
      formRow: [
        {
          elCol: [
            {
              type: 'select',
              title: '应用列表',
              id: 'appId',
              row: 24,
              disabled: false,
              required: true,
              fontSize: 16,
              options: []
            }
          ]
        },
        {
          elCol: [
            {
              type: 'select',
              title: '触发类型',
              id: 'enabledType',
              row: 24,
              disabled: false,
              required: true,
              fontSize: 16,
              options: [
                {
                  label: '手动',
                  id: '0'
                },
                {
                  label: '自动',
                  id: '1'
                }
              ]
            }
          ]
        },
        {
          elCol: [
            {
              type: 'select',
              title: '新增接口',
              id: 'addApi',
              row: 24,
              disabled: false,
              required: true,
              fontSize: 16,
              options: []
            }
          ]
        },
        {
          elCol: [
            {
              type: 'select',
              title: '修改接口',
              id: 'updateApi',
              row: 24,
              disabled: false,
              required: true,
              fontSize: 16,
              options: []
            }
          ]
        },
        {
          elCol: [
            {
              type: 'select',
              title: '删除接口',
              id: 'deleteApi',
              row: 24,
              disabled: false,
              required: true,
              fontSize: 16,
              options: []
            }
          ]
        },
        {
          elCol: [
            {
              type: 'select',
              title: '新增脚本',
              id: 'addScript',
              row: 24,
              disabled: false,
              fontSize: 16,
              options: []
            }
          ]
        },
        {
          elCol: [
            {
              type: 'select',
              title: '修改脚本',
              id: 'updateScript',
              row: 24,
              disabled: false,
              fontSize: 16,
              options: []
            }
          ]
        },
        {
          elCol: [
            {
              type: 'select',
              title: '删除脚本',
              id: 'deleteScript',
              row: 24,
              disabled: false,
              fontSize: 16,
              options: []
            }
          ]
        },
        {
          elCol: [
            {
              type: 'switch',
              title: '启用/停用',
              id: 'enabledState',
              row: 24,
              disabled: false,
              required: true,
              fontSize: 16,
              activeValue: '1',
              inactiveValue: '0'
            }
          ]
        }
      ],
      ruleForm: {},
      tableId: '',//数据源主表名称
      mainLoading: false,
      tabLoading: false,
      tableData: [],
      tableColumn: [
        {
          title: '括号',
          id: 'leftBracket'
        },
        {
          title: '字段名称',
          id: 'filedName'
        },
        {
          title: '字段编码',
          id: 'filedId'
        },
        {
          title: '运算符',
          id: 'compareType'
        },
        {
          title: '运算值',
          id: 'filedVaule'
        },
        {
          title: '连接符',
          id: 'connectionSymbol'
        },
        {
          title: '括号',
          id: 'rightParenthesis'
        },
        { title: '操作', id: 'operation' }
      ],
      compareTypeOptions: [
        {
          label: '=',
          value: '1'
        },
        {
          label: '!=',
          value: '2'
        },
        {
          label: '>',
          value: '3'
        },
        {
          label: '<',
          value: '4'
        }

      ],//对比类型options
      connectionSymbolOptions: [
        {
          label: 'and',
          value: '1'
        },
        {
          label: 'or',
          value: '2'
        }
      ],//连接符号options
      leftBracketOptions: [
        {
          label: '(',
          value: '('
        }
      ],//左括号
      rightParenthesisOptions: [
        {
          label: ')',
          value: ')'
        }
      ],//右括号
      serviceOptions: [],//主表
      labelOptions: [],//字段名称下啦
      labelDist: {}//字段名称字典
    }
  },
  methods: {
    //字段名称修改事件 需要存filedName
    filedIdChangHandle(val, row) {
      row.filedName = this.labelDist[val]
    },
    //主表名称下啦改变事件 1.请求字段名称做成下啦 2.清除表单内所有字段名称和编码
    async serviceSeleChangHadle(val, flag = true) {
      if (flag) {
        this.labelOptions = []
        this.labelDist = {}
        this.tableData.forEach(item => {
          item.filedName = ''
          item.filedId = ''
        })
      }
      if (val) {
        let obj = this.serviceOptions.find(item => {
          return val === item.id
        })
        const res = await getApiModuleApi({
          tl: 'mdmModuleService',
          as: '',
          dj: 'queryMdmServiceField'
        }, { mdmId: obj.mdmId, dbId: obj.dbId })
        res.attribute.forEach(item => {
          this.$set(this.labelDist, item.enName, item.chName)
          this.labelOptions.push({
            id: item.enName,
            label: item.chName
          })
        })
      }
    },
    //表字段字段类型下啦初始化
    async initSelect() {
      //服务名下拉
      this.serviceOptions = []
      const service = await getApiModuleApi({
        tl: 'mdmModuleService',
        as: '',
        dj: 'queryMdmService'
      }, { remark: '' })
      service.attribute.forEach(item => {
        console.log(item.dbName, 'item')
        this.serviceOptions.push({
          id: item.id,
          label: item.remark,
          dbId: item.id,
          mdmId: item.mdmId
        })
      })
      console.log(this.serviceOptions, 'this.serviceOptions')
    },
    async typeSelectChangeHanlde(val, index, indexRow, row, flag = true) {
      if (flag && row.id === 'appId') {
        this.formRow[2].elCol[0].options = []
        this.formRow[3].elCol[0].options = []
        this.formRow[4].elCol[0].options = []
        this.formRow[5].elCol[0].options = []
        this.formRow[6].elCol[0].options = []
        this.formRow[7].elCol[0].options = []
        this.$set(this.ruleForm, 'addApi', '')
        this.$set(this.ruleForm, 'updateApi', '')
        this.$set(this.ruleForm, 'deleteApi', '')
        this.$set(this.ruleForm, 'addScript', '')
        this.$set(this.ruleForm, 'updateScript', '')
        this.$set(this.ruleForm, 'deleteScript', '')
      }
      //当下啦是appid时条用接口查询该app下的所有接口用在新增、修改、删除上
      if (row.id === 'appId' && val) {
        const res = await authApi('sysApplicationApiService', '', 'queryEntity', '', {
          appId: val
        })
        res.attribute.forEach((item) => {
          this.formRow[2].elCol[0].options.push({
            id: item.id,
            label: item.apiName
          })
          this.formRow[3].elCol[0].options.push({
            id: item.id,
            label: item.apiName
          })
          this.formRow[4].elCol[0].options.push({
            id: item.id,
            label: item.apiName
          })
        })
        //插件
        const res2 = await authApi('sysApplicationService', '', 'queryAppScript', '', {
          appId: val
        })
        res2.attribute.forEach((item) => {
          this.formRow[5].elCol[0].options.push({
            id: item.id,
            label: item.scriptName
          })
          this.formRow[6].elCol[0].options.push({
            id: item.id,
            label: item.scriptName
          })
          this.formRow[7].elCol[0].options.push({
            id: item.id,
            label: item.scriptName
          })
        })
      }

    },
    //测试通过
    async typeOptionOnSubmit() {
      let flag
      //校验规则：1.允许表单为0行 2.当表单为1行时只需要判断 字段、运算符、运算值的填写 3.当表单>1行时第一行必须要填写左括号 。最后一行表单则必填右括号，非最后一行必填连接符，一行中不能同时出现左括号和右括号
      if (this.tableData.length === 1) {
        flag = this.tableData.some(item => {
          if (item.leftBracket || item.rightParenthesis || item.connectionSymbol) {
            this.$vmNews(`当仅有一行时不允许填写左右括号及连接符`)
            return true
          }
          if (!item.filedName) {
            this.$vmNews('请选择字段名称')
            return true
          }
          if (!item.compareType) {
            this.$vmNews('请选择运算符')
            return true
          }
          if (!item.filedVaule) {
            this.$vmNews('请填写运算值')
            return true
          }
        })
      } else if (this.tableData.length > 1) {
        //这边需要开始计算左括号和右括号数量 两者括号只允许左括号-右括号=1或者左括号-右括号=0否则报错
        let leftBracketNum = 0
        let rightParenthesisNum = 0
        flag = this.tableData.some((item, index) => {
          //最后一行右括号为必填
          if (index + 1 === this.tableData.length && !item.rightParenthesis) {
            this.$vmNews(`最后一行请填写右括号`)
            return true
          }
          //第一行必须填写左括号
          if (index + 1 === 1 && !item.leftBracket) {
            this.$vmNews(`首行请填写左括号`)
            return true
          }
          //除了最后一行每一行的连接符为必填
          if (index + 1 != this.tableData.length && !item.connectionSymbol) {
            this.$vmNews(`第${index + 1}请填写连接符`)
            return true
          }
          //最后一行不允许填写连接符
          if (index + 1 == this.tableData.length && item.connectionSymbol) {
            this.$vmNews(`最后一行不允许填写连接符`)
            return true
          }
          if (!item.filedName) {
            this.$vmNews(`第${index + 1}行请填写字段名称`)
            return true
          }
          if (!item.compareType) {
            this.$vmNews(`第${index + 1}行请填写运算符`)
            return true
          }
          if (!item.filedVaule) {
            this.$vmNews(`第${index + 1}行请填写运算值`)
            return true
          }
          if (item.leftBracket && item.rightParenthesis) {
            this.$vmNews(`第${index + 1}行中不允许同时存在左括号和右括号`)
            return true
          }
          //开始判断左右括号是否一致
          if (item.leftBracket) {
            leftBracketNum++
            let num = leftBracketNum - rightParenthesisNum
            if (num !== 0 && num !== 1) {
              this.$vmNews(`第${index + 1}行中左括号填写不符合规则请重新填写`)
              return true
            }
          }
          if (item.rightParenthesis) {
            rightParenthesisNum++
            let num = leftBracketNum - rightParenthesisNum
            if (num !== 0 && num !== 1) {
              this.$vmNews(`第${index + 1}行中右括号填写不符合规则请重新填写`)
              return true
            }
          }
        })
      }
      if (flag) return
      let params = {
        ...this.ruleForm,
        dbId: this.tableId,
        mdmId: this.$route.query.id,
        mdmModuleDistributeDetailEntities: this.tableData
      }
      if (params.id) {
        this.openLoading('submit')
        const res = await authApi('mdmModuleService', '', 'updateMdmDistribute', '', params)
        this.$vmNews('保存成功', 'success')
        this.$emit('saveSuccessHandle')
      } else {
        this.openLoading('submit')
        const res = await authApi('mdmModuleService', '', 'saveMdmDistribute', '', params)
        this.$vmNews('保存成功', 'success')
        this.$emit('saveSuccessHandle')
      }
    },
    addRowHandle() {
      this.tableData.push({
        'leftBracket': '',//左括号
        'filedName': '',//字段名
        'compareType': '',//对比类型 1、等于 2、不等于 3、大于 4、小于
        'filedVaule': '',//值
        'connectionSymbol': '',// 连接符号 1\and 2\or
        'rightParenthesis': ''// 右括号
      })
    },
    //删除
    activedOnFunc(row) {
      this.tableData.splice(row.index, 1)
    },
    //获取应用下啦
    async getAppList() {
      const res = await authApi('sysApplicationService', '', 'queryEntity', '', {})
      console.log(res)
      this.formRow[0].elCol[0].options = []
      res.attribute.forEach(item => {
        this.formRow[0].elCol[0].options.push({
          id: item.id,
          label: item.name
        })
      })

    },
    //编辑获取数据
    async getrowDetails(id) {
      const res = await authApi('mdmModuleService', '', 'getMdmDistribute', '', {
        id
      })
      this.ruleForm = res.attribute
      this.tableId = this.ruleForm.dbId
      this.tableData = res.attribute.mdmModuleDistributeDetailEntities
      console.log(this.tableData, '?')
      this.typeSelectChangeHanlde(this.ruleForm.appId, 0, 0, { id: 'appId' }, false)
      this.serviceSeleChangHadle(this.ruleForm.dbId, false)
    }
  },
  created() {
    this.getAppList()
    this.initSelect()
  },
  components: {
    BaseTable,
    baseNewForm
  }
}
</script>


<style scoped lang="scss">
.bigTitle {
  border-top: 1px solid #EBEBEB;
  padding-top: 20px;
  font-family: PingFangSC, PingFang SC;
  font-weight: 600;
  font-size: 16px;
  color: #333333;
  line-height: 22px;
  text-align: left;
  font-style: normal;
}

.tableName {
  display: flex;
  align-items: center;
  margin: 30px 0;

  .title {
    margin-right: 20px;
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: #333333;
    line-height: 20px;
    text-align: left;
    font-style: normal;
  }
}

.receiptsAddRow {
  margin-top: 30px;
  border: 1px dotted #ccc;
  text-align: center;
  height: 50px;
  line-height: 50px;
}

.btnList {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;

  .deleBtn {
    cursor: pointer;
    margin-left: 10px;
    width: 24px;
    height: 24px;
    background: #EBEBED;
    border-radius: 6px;
    display: flex;
    justify-content: center;
    align-items: center;

    > img {
      width: 10px;
      height: 10px;
    }
  }
}
</style>
