<template>
  <div class="wrap">
    <!--数据表-->
    <div class="mainTable">
      <div class="bigTitle">数据表</div>
      <div class="rule">
        <div class="name">单据规则</div>
        <template v-if="!receiptsTableData.length">
          <div class="value">尚未设置</div>
        </template>
        <template v-else>
          <div class="value">
            <div class="receiptsItem" v-for="(item,index) in receiptsTableData">{{ item.dbValue }}</div>
          </div>
        </template>
        <div class="btn" @click="ruleAddHandle">
          <img src="./images/设置.png" alt="">
        </div>
      </div>
      <div class="table">
        <BaseTable
          ref="mainTable"
          :tableData="mainTableData"
          :tabLoading="mainTabLoading"
          :tableColumn="mainTableColumn"
          :border="false"
          tableMaxHeight="600"
          :highlightCurrent="true"
          @radioChange="mainOnClick"
        >
          <template #dbType="{row}">
            {{ row.dbType === '1' ? '主表' : '子表' }}
          </template>
          <template #operation="{row}">
            <div class="btnList">
              <div class="settingBtn" @click="mainTableEditHandle(row)">
                <img src="./images/设置.png" alt="">
              </div>
              <div class="deleBtn" @click="mainDeleOnFunc(row)">
                <img src="./images/删除.png" alt="">
              </div>
            </div>
          </template>
        </BaseTable>
        <div class="mainAddRow">
          <el-link
            type="primary"
            @click="addMainAddRow"
            :underline="false"
          >+ 数据表添加
          </el-link
          >
        </div>
      </div>
    </div>
    <!--    表字段-->
    <div class="sonTable">
      <div class="bigTitle">表字段</div>
      <div class="table">
        <BaseTable
          ref="activedTable"
          :tableData="activedTableData"
          :tabLoading="activedTabLoading"
          :tableColumn="activedTableColumn"
          :border="false"
          tableMaxHeight="650"
          :highlightCurrent="true"
          @radioChange="activedOnClick"
          @onFunc="activedOnFunc"
        >
          <template #filedType="{row}">
            {{ dataTypeDist[row.filedType] }}
          </template>
          <template #operation="{row}">
            <div class="btnList">
              <div class="settingBtn" @click="sonTableEditHandle(row)">
                <img src="./images/设置.png" alt="">
              </div>
              <div class="deleBtn" @click="activedOnFunc(row)">
                <img src="./images/删除.png" alt="">
              </div>
            </div>
          </template>
        </BaseTable>
        <div class="mainAddRow" v-if="mainTempClick.id">
          <el-link
            v-if="mainTempClick.id"
            type="primary"
            @click="activedAddRow"
            :underline="false"
          >+ 表字段添加
          </el-link
          >
        </div>
      </div>
    </div>
    <!--    单据规则-->
    <base-right-dialog
      ref="baseRightDialog"
      :footerShow="true"
      :dialogVisible.sync="ruleAddDialogShow"
      title="单据规则"
      @handleClose="ruleAddDialogShow=false"
      :submitShow="true"
      :size="'50%'"
      @handleConfirmClick="ruleAddSaveHanlde"
    >
      <div class="receiptsTable">
        <ruleAddTable ref="ruleAddTable"></ruleAddTable>
      </div>
    </base-right-dialog>
    <!--    数据表 -->
    <base-right-dialog
      ref="mainTableAddtDialog"
      :footerShow="true"
      :dialogVisible.sync="mainTableDialogShow"
      title="数据表"
      @handleClose="mainTableDialogShow=false"
      :submitShow="true"
      :size="'30%'"
      @handleConfirmClick="mainTableSaveHandle"
    >
      <div class="mainTable">
        <mainTable ref="mainTable"></mainTable>
      </div>
    </base-right-dialog>
    <!--    表字段-->
    <base-right-dialog
      ref="sonTableAddtDialog"
      :footerShow="true"
      :dialogVisible.sync="sonTableDialogShow"
      title="表字段"
      @handleClose="sonTableDialogShow=false"
      :submitShow="true"
      :size="'40%'"
      @handleConfirmClick="sonTableSaveHandle"
    >
      <div class="mainTable">
        <sonTable ref="sonTable" :activedTableData="activedTableData" :mainTempClick="mainTempClick"
                  @sonSaveHandle="sonSaveHandle"
        ></sonTable>
      </div>
    </base-right-dialog>
  </div>
</template>

<script>
import sonTable from '@/views/masterDataOptions/dataOrigin/sonTable.vue'
import mainTable from '@/views/masterDataOptions/dataOrigin/mainTable.vue'
import ruleAddTable from '@/views/masterDataOptions/dataOrigin/ruleAddTable.vue'
import BaseTable from '@/views/intergrationTask/compoments/baseTable.vue'
import configData from './configData'
import { getApiModuleApi } from '@/api/apiChunks/index.js'
import baseNewForm from '../compoments/baseNewForm'
import { deepClone } from '@/utils/index.js'
import baseDialog from '@/views/integrationOption/compoments/baseDialog'
import baseForm from '@/components/base/baseNewForm/index.vue'
import baseRightDialog from '@/components/base/baseRightDialog/index.vue'
import { authApi } from '@/api/apis/auth'

export default {
  data() {
    return {
      mainTempClick: {},//数据表当前点击行
      mainTableData: [],//主表数据
      mainTabLoading: false,//主表loading
      mainTableColumn: [
        { title: '英文名', id: 'dbName' },
        { title: '表类型', id: 'dbType' },
        { title: '表说明', id: 'remark' },
        { title: '操作', id: 'operation' }
      ],
      mainFunData: [],//主表操栏
      activedTableData: [],//子表数据（单击主表后赋值）
      activedTabLoading: false,//选中表loading
      activedTableColumn: [
        { title: '中文名', id: 'chName' },
        { title: '英文名', id: 'enName' },
        { title: '字段类型', id: 'filedType' },
        { title: '长度', id: 'filedLength' },
        { title: '操作', id: 'operation' }
      ],//子表行数据
      activedFunData: [
        {
          text: '删除',
          color: 'red'
        }
      ],//子表操作栏
      ruleAddDialogShow: false,//单据规则
      receiptsTableData: [],//单据规则表单
      mainTableDialogShow: false,//主数据弹窗
      //数据类型字段
      dataTypeDist: {},
      //表字段下啦
      fieldTypeOptions: [],
      sonTableDialogShow: false,//字表dialog显示
      serviceOptions: []//表字段服务名称下啦

    }
  },
  methods: {
    //表字段字段类型下啦初始化
    async initSelect() {
      //数据类型下拉
      const type = await getApiModuleApi({
        tl: 'generalServiceImpl',
        as: 'dictionaryshop',
        dj: 'selectDictionaryshop'
      }, { tab_name: 'mdm', column_name: 'mdm_filed_type' })
      this.fieldTypeOptions = []
      type.attribute.forEach(item => {
        //创造数据字段给表单插槽显示（字段类型）
        this.$set(this.dataTypeDist, item.column_value, item.column_content)
        this.fieldTypeOptions.push({
          label: item.column_content,
          id: item.column_value
        })
      })
      this.serviceOptions = []
      //服务名下拉
      const service = await getApiModuleApi({
        tl: 'mdmModuleService',
        as: '',
        dj: 'queryMdmService'
      }, { remark: '' })
      service.attribute.forEach(item => {
        console.log(item, 'item')
        this.serviceOptions.push({
          id: item.dbName,
          label: item.remark,
          dbId: item.id,
          mdmId: item.mdmId

        })
      })
    },
    // 主表上方表格行点击
    async mainOnClick(val) {
      if (val.index === -1) return
      console.log(val)
      //将当前点击行存储
      this.mainTempClick = val
      //请求数据表对应的表字段
      const res = await authApi('mdmModuleService', '', 'queryMdmDbField', '', {
        mdmId: this.$route.query.id,
        dbId: this.mainTempClick.id
      })
      this.activedTableData = res.attribute
    },
    // 主表按钮(删除）
    mainDeleOnFunc(row, item) {
      console.log(row, 'row')
      let msg = row.dbType == 1 ? '删除主表将会导致所有相关子表一并删除，是否确认继续删除操作？' : '确定是否删除？'
      this.$confirm(msg)
        .then(async(_) => {
          this.openLoading('submit')
          const res = await authApi('mdmModuleService', '', 'deleteMdmDb', '', {
            mdmId: this.$route.query.id,
            ...row
          })
          this.$vmNews('删除成功！', 'success')
          if (this.mainTempClick.id === row.id || row.dbType == 1) {
            this.activedTableData = []
            this.mainTempClick = {}
          }
          this.getMainTableHandle()
        })
        .catch((_) => {
        })
    },
    //数据表添加按钮
    addMainAddRow() {
      if (!this.receiptsTableData.length) {
        this.$vmNews('请添加单据规则后，再添加数据表。')
        return
      }
      this.mainTableDialogShow = true
      this.$nextTick(() => {
        //重置表单
        this.$refs.mainTable.$refs.mainOptionForm.resetFields()
        this.$refs.mainTable.mainOptionForm = {}
        //将英文名改为可编辑状态
        this.$refs.mainTable.mainOptionRow[0].elCol.disabled = false
      })
    },
    //数据表编辑
    mainTableEditHandle(row) {
      this.mainTableDialogShow = true
      this.$nextTick(() => {
        //重置表单
        this.$refs.mainTable.$refs.mainOptionForm.resetFields()
        this.$refs.mainTable.mainOptionForm = JSON.parse(JSON.stringify(row))
        //将英文名改为可编辑状态
        this.$refs.mainTable.mainOptionRow[0].elCol.disabled = true
      })
    },
    //表字段单击事件
    activedOnClick(val) {
    },
    //表字段点击操作
    activedOnFunc(row) {
      this.$confirm('确定删除？')
        .then(async(_) => {
          this.openLoading('submit')
          const res = await authApi('mdmModuleService', '', 'deleteMdmDbField', '', {
            id: row.id,
            mdmId: this.$route.query.id,
            dbId: this.mainTempClick.id,
            dbName: this.mainTempClick.dbName,
            enName: row.enName,
            filedType: row.filedType
          })
          this.$vmNews('删除成功', 'success')
          this.mainOnClick(this.mainTempClick)
          this.activedTableData.splice(row.index, 1)
        })
        .catch((_) => {
        })
    },
    //表字段点击设置
    sonTableEditHandle(row) {
      this.sonTableDialogShow = true
      this.$nextTick(() => {
        //重置一切表单
        this.$refs.sonTable.$refs.optionForm.resetFields()
        this.$refs.sonTable.$refs.typeOptionForm.resetFields()
        this.$refs.sonTable.$refs.propertyForm.resetFields()
        this.$refs.sonTable.optionRuleForm = {}
        this.$refs.sonTable.typeOptionRuleForm = {}
        this.$refs.sonTable.propertyRuleForm = {}
        this.$refs.sonTable.propertyActiveList = []
        this.$refs.sonTable.propertyFormRow = []
        this.$refs.sonTable.typeOptionFormRow = []
        //字段类型下啦
        this.$refs.sonTable.optionFormRow[2].elCol[0].options = this.fieldTypeOptions
        this.$refs.sonTable.serviceOptions = this.serviceOptions
        this.$refs.sonTable.activedOnClick(row)

      })
    },
    //表字段添加按钮
    activedAddRow() {
      this.sonTableDialogShow = true
      this.$nextTick(() => {
        //重置一切表单
        this.$refs.sonTable.$refs.optionForm.resetFields()
        this.$refs.sonTable.$refs.typeOptionForm.resetFields()
        this.$refs.sonTable.$refs.propertyForm.resetFields()
        this.$refs.sonTable.optionRuleForm = {}
        this.$set(this.$refs.sonTable.optionRuleForm, 'required', false)
        this.$set(this.$refs.sonTable.optionRuleForm, 'disabled', false)
        this.$refs.sonTable.typeOptionRuleForm = {}
        this.$refs.sonTable.propertyRuleForm = {}
        this.$refs.sonTable.propertyActiveList = []
        this.$refs.sonTable.propertyFormRow = []
        this.$refs.sonTable.typeOptionFormRow = []
        this.$refs.sonTable.activedTableRow = {}
        //字段类型下啦
        this.$refs.sonTable.optionFormRow[2].elCol[0].options = this.fieldTypeOptions
        this.$refs.sonTable.serviceOptions = this.serviceOptions

      })
    },
    //单据规则方法打开
    ruleAddHandle() {
      this.ruleAddDialogShow = true
      this.$nextTick(() => {
        this.$refs.ruleAddTable.ruleAddTableData = JSON.parse(JSON.stringify(this.receiptsTableData))
      })

    },
    //单据规则添加方法(保存）
    async ruleAddSaveHanlde() {
      let tempTableData = this.$refs.ruleAddTable.ruleAddTableData
      let type = false
      let flag = tempTableData.some((item, index) => {
        if (!item.dbType || !item.dbValue) {
          this.$vmNews(`请选择${index + 1}行的类型并填写或选择规则`, 'warning')
          return true
        } else if (item.dbType === '4' && index + 1 !== tempTableData.length) {
          type = true
          this.$vmNews(`流水号只允许在最后一行`, 'warning')
          return true
        } else if (item.dbType === '4') {
          type = true
        }
      })
      if (!type) {
        this.$vmNews(`请添加流水号`, 'warning')
        return
      }
      if (flag) return
      this.openLoading('submit')
      const res = await authApi('mdmModuleService', '', 'saveOrUpdateMdmTableCodeRule', '', {
        id: this.$route.query.id,
        mdmTableCodeRuleEntityList: tempTableData
      })
      this.ruleAddDialogShow = false
      this.$vmNews('添加单据规则成功', 'success')
      //调用单据规则
      this.getRuleHandle()
    },
    //单据规则获取
    async getRuleHandle() {
      this.openLoading('submit')
      const res = await authApi('mdmModuleService', '', 'getMdmTableCodeRule', '', {
        mdmId: this.$route.query.id
      })
      this.receiptsTableData = res.attribute
    },
    //数据表保存
    mainTableSaveHandle() {
      this.$refs.mainTable.$refs.mainOptionForm.$refs['ruleForm'].validate(async(valid) => {
        if (valid) {
          //主数据英文名黑名单
          let blacklist = ['id', 'document_rule', 'document_rule_num', 'data_status', 'add_status', 'update_status', 'delete_status', 'sorts', 'create_user_id', 'create_time', 'modify_user_id', 'modify_time', 'sts', 'org_id', 'company_id', 'data_id']
          let form = this.$refs.mainTable.mainOptionForm
          //判断黑名单
          if (blacklist.includes(form.dbName)) {
            this.$vmNews('当前英文名为系统默认字段，请修改')
            return
          }
          //判断是主表还是子表 "dbType":"2",//类型 1、主表 2、明细
          console.log(this.mainTableData.length && !form.id, 'this.mainTableData.length && !form.id', form, this.mainTableData.length)
          if (!form.id) {
            if (this.mainTableData.length) {
              this.$set(form, 'dbType', 2)
            } else {
              this.$set(form, 'dbType', 1)
            }
          }

          //判断有没有id如果有走编辑 没有走新增
          if (form.id) {
            this.openLoading('submit')
            const res = await authApi('mdmModuleService', '', 'updateMdmDb', '', {
              mdmId: this.$route.query.id,
              ...form
            })
            if (res.status == 200) {
              this.$vmNews('保存成功', 'success')
              this.mainTableDialogShow = false
              this.getMainTableHandle()
              this.initSelect()
            }
          } else {
            this.openLoading('submit')
            const res = await authApi('mdmModuleService', '', 'saveMdmDb', '', {
              mdmId: this.$route.query.id,
              ...form
            })
            if (res.status == 200) {
              this.$vmNews('保存成功', 'success')
              this.mainTableDialogShow = false
              this.getMainTableHandle()
              this.initSelect()
            }
          }

        } else {
          return false
        }
      })
    },
    //表字段保存
    sonTableSaveHandle() {
      this.$refs.sonTable.$refs.optionForm.submitForm()

    },
    //获取数据表
    async getMainTableHandle() {
      this.openLoading('detail')
      const res = await authApi('mdmModuleService', '', 'queryMdmDb', '', {
        mdmId: this.$route.query.id
      })
      this.mainTableData = res.attribute
    },
    //表字段校验通过正式开始保存
    async sonSaveHandle(params) {
      if (params.id) {
        this.openLoading('submit')
        const res = await authApi('mdmModuleService', '', 'updateMdmDbField', '', params)
        this.$vmNews('保存成功！', 'success')
        this.sonTableDialogShow = false
        //重新请求表字段
        this.mainOnClick(this.mainTempClick)

      } else {
        this.openLoading('submit')
        const res = await authApi('mdmModuleService', '', 'saveMdmDbField', '', params)
        this.$vmNews('保存成功！', 'success')
        this.sonTableDialogShow = false
        //重新请求表字段
        this.mainOnClick(this.mainTempClick)
      }

    }
  },
  components: {
    baseRightDialog, baseForm,
    baseNewForm,
    BaseTable,
    baseDialog,
    ruleAddTable,
    mainTable,
    sonTable
  },
  created() {
    //调用单据规则
    this.getRuleHandle()
    //调用获取数据表
    this.getMainTableHandle()
    //表字段的数据类型下啦获取
    this.initSelect()
    //调用左侧选中状态
    this.$emit('flashActive', 1)
  },
  watch: {},
  computed: {}
}
</script>

<style scoped lang="scss">
::v-deep .el-button {
  border-radius: 4px;
}

::v-deep .el-form-item {
  display: block !important;
}

.wrap {
  display: flex;
  background-color: #fff;
  margin-left: 5px;
  border-radius: 8px;
  height: calc(100%);

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

  .bigTitle {
    font-family: PingFangSC, PingFang SC;
    font-weight: 600;
    font-size: 18px;
    color: #333333;
    line-height: 20px;
    text-align: left;
    font-style: normal;
  }

  .mainTable {
    flex: 1;
    padding: 30px 20px 20px;
    border-right: 1px solid #EBEBEB;;

    .rule {
      margin-top: 20px;
      display: flex;
      align-items: center;
      width: 100%;

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

      .value {
        display: flex;
        align-items: center;
      }

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

        > img {
          width: 15px;
          height: 15px;
        }
      }
    }

    .table {
      margin-top: 20px;


    }
  }

  .sonTable {
    flex: 1;
    padding: 30px 20px 20px;

    .table {
      margin-top: 20px;
    }
  }
}

.btnList {
  display: flex;
  align-items: center;
  justify-content: center;

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

    > img {
      width: 10px;
      height: 10px;
    }
  }

  .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>
