<template>
  <div class="wrap">
    <div class="tree" v-if="$route.query.viewType === '1'" style="flex:0.2">
      <BaseMenuTree
        :menuData="treeData"
        :filterShow="false"
        :Allshow="false"
        :treeButton="false"
        :filterButtonShow="false"
        style="height: 100%"
        :treeProps="treeProps"
        @handleNodeClick="homeHandleNodeClick"
        ref="menuTree"
      ></BaseMenuTree>
    </div>
    <div class="main" :style="{flex:$route.query.viewType === '1'?0.8:1}" v-loading="mainLoading">
      <div class="top">
        <div class="search">
          <BaseNewForm
            v-loading="searchLoading"
            refName="searchForm"
            :formRow="searchFormRow"
            :formRule="false"
            :ruleForm="searchForm"
            :newFlag="true"
            :treeSelectInfo="treeSelectInfo"
            :isFunBtn="false"
          ></BaseNewForm>
        </div>
        <div class="btnList">
          <div class="btnItem" v-for="item in searchButton" :key="item.buttonType">
            <el-button
              type="primary"
              size="mini"
              @click="buttonHandle(item)"
            >{{ item.buttonName }}
            </el-button>
          </div>
        </div>
      </div>
      <div class="table">
        <BaseTable
          ref="mainTable"
          :treeSelectInfo="treeSelectInfo"
          :tableData="tableData"
          :tableColumn="tableColumn"
          :funData="mainFunData"
          :funWidth="funWidth"
          :showIndex="true"
          :tabLoading="mainTabLoading"
          @onFunc="tableButtonHandle"
          @selectValueGeT="selectValueGeTHandle"
          :tableHeight="'67vh'"
          :border="false"
        >
        </BaseTable>
        <div class="nextPage">
          <BasePage
            :pageModel="pageModel"
            @update:pageModel="currentChangeHandle"
          ></BasePage>
        </div>
      </div>
    </div v->
    <baseDialog v-model="dialogShow" @confirm="dialogConfirm" :lookFlag="lookFlag">
      <h1 style="margin: 20px 0; font-size: 20px; font-weight: 700">
        基本信息
      </h1>
      <div class="dialogForm" v-if="dialogShow" style="padding: 0 20px">
        <BaseNewForm
          :treeSelectInfo="treeSelectInfo"
          :loading="dialogCommitLoading"
          :formRow="formRow"
          :ruleForm="ruleForm"
          :lookFlag="lookFlag"
          :newFlag="newFlag"
          @onSubmit="onSubmitHandele"
          :isFunBtn="false"
          ref="dialogForm"
        ></BaseNewForm>
      </div v->
      <template v-for="(item, index) in dialogTabaleInfo">
        <div class="sonTable">
          <h1 style="margin: 20px 0; font-size: 20px; font-weight: 700">
            {{ item.title }}
          </h1>
          <BaseTableForm
            :lookflag="lookFlag"
            :showIndex="true"
            :treeSelectInfo="treeSelectInfo"
            :indexOperate="true"
            :tableInfo="item"
            @newRow="dialogTableAddHandle"
            @onFunc="dialogTableDeleHandle"
            :funData="dialogfunData"
            :border="false"
            table-height="30vh"
          ></BaseTableForm>
        </div>

      </template>
    </baseDialog>
    <!--    分发任务dialog-->
    <baseDialog v-model="sendShow" :footerShow="false">
      <baseTable
        :tableData="sendTableData"
        :tableColumn="sendTableColumn">
        <template v-slot:status="{row}">
          {{ sendDist[row.status] }}
        </template>
        <template v-slot:fun="{row}">
          <el-button v-if="row.status === '1'||row.status === '2'" type="danger" @click="sendRowHandle(row)">删除
          </el-button>
          <el-button v-if="row.status === '3'||row.status === '4'" type="primary" @click="sendRowHandle(row)">下发
          </el-button>
        </template>
      </baseTable>
    </baseDialog>
  </div>
</template>
<script>
import {deepClone} from "@/utils/index.js";
import {getUserModuleApi} from "@/api/integrationOption/integrationOption.js";
import BaseNewForm from "./compoments/baseNewForm";
import BaseTable from "./compoments/baseTable";
import BasePage from "./compoments/basePage.vue";
import baseDialog from "@/views/integrationOption/compoments/baseDialog";
import BaseTableForm from "./compoments/baseTableForm_v2.vue";
import BaseMenuTree from "@/views/intergrationTask/compoments/baseMenuTree.vue";

export default {
  data() {
    return {
      treeObj: {
        label: "",
        upId: ""
      },
      sendDist: {
        "1": "发送成功",
        "2": "发送中",
        "3": "发送失败",
        "4": "未发送"
      },
      sendShow: false,//分发任务dialog
      sendTableColumn: [
        {
          id: 'name',
          title: "应用"
        },
        {
          id: 'status',
          title: "状态"
        },
        {
          id: 'msg',
          title: "信息"
        },
        {
          id: "fun",
          title: "操作"
        }

      ],
      sendTableData: [],
      //搜索相关
      searchFormRow: [],
      searchForm: {},
      searchLoading: false,
      //按钮相关
      searchButton: [],
      mainTableName: "",
      // 主表按钮
      mainLoading: false,
      mainFunData: [],
      mainActiveRow: {},
      mainTabLoading: false,
      tableData: [],
      tableColumn: [],
      // 分页器
      pageModel: {
        total: 0,
        pageIndex: 1,
        limit: 10,
      },
      //dialog相关
      dialogShow: false,
      dialogCommitLoading: false,
      formRow: [],
      ruleForm: {},
      lookFlag: false,
      newFlag: false,
      dialogTabaleInfo: [],
      dialogfunData: [{text: "删除", type: "dele", color: 'red'}],
      dialogTableLoading: false,
      dialogFormName: "",
      //树相关
      treeProps: {
        children: "children",
        label: "label",
      },
      treeData: [],
      treeActiveRow: {},
      treeSelectInfo: {},
    }
  },
  methods: {
    async init() {
      this.mainLoading = true
      const res = await getUserModuleApi({
        tl: "mdmService",
        as: "mdmService",
        dj: "queryMdmShow",
      }, {mdmCode: this.$route.meta.mdmCode})
      // 树处理
      if (this.$route.query.viewType === '1') {
        this.treeObj.label = res.attribute.mdmModuleViewEntity.viewFiled
        this.treeObj.upId = res.attribute.mdmModuleViewEntity.upIdFiled
        this.initTree(res.attribute.mdmModuleViewEntity.viewFiled, res.attribute.mdmModuleViewEntity.upIdFiled)
      }
      //搜索数据处理
      res.attribute.queryList.forEach(item => {
        item.ruleList.forEach(ele => {
          item[ele.ruleCode] = ele.ruleValue
          item['id'] = item.enName
        })
      })
      this.searchFormRow = []
      this.baseFormRowDispose(res.attribute.queryList, this.searchFormRow)
      //按钮框处理
      let funDataBtn = {
        edit: true,
        view: true,
        dele: true,
        send: true,
      }
      this.searchButton = []
      this.mainFunData = []
      res.attribute.buttonList.forEach(item => {
        if (funDataBtn[item.buttonType]) {
          this.mainFunData.push({
            text: item.buttonName,
            type: item.buttonType
          })
        } else {
          this.searchButton.push(item)
        }
      })
      //主表处理
      res.attribute.listList.forEach(item => {
        this.mainTableName = item.dbName
        item.ruleList.forEach(ele => {
          item[ele.ruleCode] = ele.ruleValue
          item['id'] = item.enName
        })
      })
      this.tableColumn = res.attribute.listList
      this.initTableData(this.mainTableName)
      this.mainLoading = false
    },
    async initTree(label, upId, obj = {}) {
      if (this.$route.query.viewType !== '1') return
      const res = await getUserModuleApi({
        tl: "mdmService",
        as: "mdmService",
        dj: "queryMdmShowTreeData",
      }, {
        mdmCode: this.$route.meta.mdmCode,
        label,
        upId
      })

      if (res.status === '200') {
        this.treeData = res.attribute
      }
    },
    async initTableData(name, obj = {}) {
      this.mainTabLoading = true
      const res = await getUserModuleApi({
        tl: "mdmService",
        as: "mdmService",
        dj: "queryMdmShowData",
      }, {
        pageNum: this.pageModel.pageIndex,
        pageSize: this.pageModel.limit,
        tableName: name,
        ...obj
      })
      this.mainTabLoading = false
      this.pageModel.total = res.attribute.total
      this.tableData = res.attribute.list
    },
    // 列表处理（算row）
    baseFormRowDispose(arr, resultArr) {
      let searchSpan = 0
      let tempArr = [];
      arr.forEach(item => {
        let spanNum = item.row * 1 || 12;
        searchSpan += spanNum;
        if (searchSpan > 24) {
          resultArr.push({elCol: tempArr});
          searchSpan = spanNum;
          tempArr = [];
          tempArr.push(item);
        } else {
          tempArr.push(item);
        }
      })
      if (tempArr.length) {
        resultArr.push({elCol: tempArr});
      }
    },
    //按钮事件
    async buttonHandle(item) {
      if (item.buttonType === 'search') {
        this.searchHandle()
      } else if (item.buttonType === 'resize') {
        this.searchForm = {}
      } else if (item.buttonType === 'new') {
        this.newDialogHandle()
      } else if (item.buttonType === 'contrast') {

      }
    },
    //主表相关事件
    //主表下拉找值
    selectValueGeTHandle(item, row, data) {
      this.$set(this.tableData[row.index], item.id, data);
      this.$set(this.tableData[row.index], "selectflag", true);
    },
    //主表按钮
    async tableButtonHandle(row, item) {
      if (item.type === 'edit') {
        this.editDialogHanlde(row.id)
      } else if (item.type === 'view') {
        this.viewDIalogHandle(row.id)
      } else if (item.type === 'dele') {
        this.$confirm("是否删除此行?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.deleRowHanlde(row.id)

          })
          .catch((error) => {
          });
      } else if (item.type === 'send') {
        this.sendHandle(row.id)
      }
    },
    // 分页器更新数据
    currentChangeHandle(pageModel) {
      this.pageModel = pageModel;
      this.$nextTick(() => {
        this.searchHandle()
      });
    },
    //dialog表单通过验证准备提交
    async onSubmitHandele() {
      //新增
      if (this.newFlag) {
        let params = {
          mdmCode: this.$route.meta.mdmCode,
          data: {}
        }
        params.data[this.dialogFormName] = deepClone(this.ruleForm)
        this.dialogTabaleInfo.forEach(item => {
          params.data[item.name] = item.tableData.slice(0, -1)
        })
        const res = await getUserModuleApi({
          tl: "mdmService",
          as: "mdmService",
          dj: "saveMdmShowDetailsData",
        }, params)
        if (res.status === '200') {
          this.initTree(this.treeObj.label, this.treeObj.upId)
          this.$vmNews("新建成功", "success")
          this.searchHandle()
          this.dialogShow = false
        }
      } else {
        //修改
        let params = {
          mdmCode: this.$route.meta.mdmCode,
          data: {}
        }
        params.data[this.dialogFormName] = deepClone(this.ruleForm)
        this.dialogTabaleInfo.forEach(item => {
          params.data[item.name] = item.tableData.slice(0, -1)
        })
        const res = await getUserModuleApi({
          tl: "mdmService",
          as: "mdmService",
          dj: "updateMdmShowDetailsData",
        }, params)
        if (res.status === '200') {
          this.initTree(this.treeObj.label, this.treeObj.upId)
          this.$vmNews("修改成功", "success")
          this.searchHandle()
          this.dialogShow = false
        }
      }

    },
    dialogTableAddHandle(info, index) {
      this.dialogTabaleInfo[index].tableData.push({});
    },
    dialogTableDeleHandle(row, item, tableInfo, index) {
      if (item.type === "dele") {
        this.$confirm("是否删除此行?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.dialogTabaleInfo[index].tableData.splice(row.index, 1);
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          })
          .catch((error) => {
          });
      }
    },
    //dialog表格提交
    dialogConfirm() {
      this.$refs.dialogForm.submitForm()
    },
    //点击新增dialog处理事件
    async newDialogHandle() {
      this.ruleForm = {}
      this.newFlag = true
      this.lookFlag = false
      const res = await getUserModuleApi({
        tl: "mdmService",
        as: "mdmService",
        dj: "queryMdmShowDetails"
      }, {
        mdmCode: this.$route.meta.mdmCode,
        showType: "3"
      })
      // 主表数据处理
      res.attribute.mainMdmModuleDb.sublistMdmModuleDbFileds.forEach(item => {
        item.mdmModuleDbFiledsRules.forEach(ele => {
          if (ele.ruleCode === "required" || ele.ruleCode === "disabled") {
            if (!ele.ruleValue) {
              item[ele.ruleCode] = false
            } else {
              item[ele.ruleCode] = JSON.parse(ele.ruleValue)
            }
          } else {
            item[ele.ruleCode] = ele.ruleValue
          }
          item['id'] = item.enName
        })
      })
      this.dialogFormName = res.attribute.mainMdmModuleDb.dbName
      this.formRow = []
      this.baseFormRowDispose(res.attribute.mainMdmModuleDb.sublistMdmModuleDbFileds, this.formRow)
      //子表处理
      this.dialogTabaleInfo = []
      res.attribute.sublistMdmModuleDb.forEach(table => {
        table.sublistMdmModuleDbFileds.forEach(item => {
          item.mdmModuleDbFiledsRules.forEach(ele => {
            if (ele.ruleCode === "required" || ele.ruleCode === "disabled") {
              if (!ele.ruleValue) {
                item[ele.ruleCode] = false
              } else {
                item[ele.ruleCode] = JSON.parse(ele.ruleValue)
              }

            } else {
              item[ele.ruleCode] = ele.ruleValue
            }
            item['id'] = item.enName
          })
        })
        table.tableData = {}
        table.detailFields = []
        let tempObj = {
          tableData: [{}],
          detailFields: deepClone(table.sublistMdmModuleDbFileds),
          title: table.remark,
          name: table.dbName,
        }
        this.dialogTabaleInfo.push({...tempObj})
      })
      this.dialogShow = true
    },
    searchHandle() {
      let obj = {}
      this.searchFormRow.forEach(item => {
        item.elCol.forEach(ele => {
          if (this.searchForm[ele.enName]) {
            if (obj[ele.dbName]) {
              obj[ele.dbName].push({
                fields: ele.enName,
                fieldsType: ele.filedType,
                values: this.searchForm[ele.enName]
              })
            } else {
              obj[ele.dbName] = [{
                fields: ele.enName,
                fieldsType: ele.filedType,
                values: this.searchForm[ele.enName]
              }]
            }
          }
        })
      })
      let params = {
        queryCondition: [],
        detailQueryCondition: [],
      }
      Object.keys(obj).forEach(key => {
        if (key === this.mainTableName) {
          params.queryCondition = obj[key]
        } else {
          let temp = {
            tableName: key,
            queryCondition: obj[key]
          }
          params.detailQueryCondition.push(temp)
        }
      })
      if (this.treeActiveRow.id) {
        let obj = {
          fields: "id",
          values: this.treeActiveRow.arrId,
          fieldsType: '5'
        }
        params.queryCondition.push(obj)
      }
      this.initTableData(this.mainTableName, params)
    },
    //编辑dialog处理事件
    async editDialogHanlde(id) {
      this.newFlag = false
      this.lookFlag = false
      //初始化模版
      const res = await getUserModuleApi({
        tl: "mdmService",
        as: "mdmService",
        dj: "queryMdmShowDetails"
      }, {
        mdmCode: this.$route.meta.mdmCode,
        showType: "4"
      })
      res.attribute.mainMdmModuleDb.sublistMdmModuleDbFileds.forEach(item => {
          item.mdmModuleDbFiledsRules.forEach(ele => {
            if (ele.ruleCode === "required" || ele.ruleCode === "disabled") {
              if (!ele.ruleValue) {
                item[ele.ruleCode] = false
              } else {
                item[ele.ruleCode] = JSON.parse(ele.ruleValue)
              }
            } else {
              item[ele.ruleCode] = ele.ruleValue
            }


            item['id'] = item.enName
          })
        }
      )
      this.dialogFormName = res.attribute.mainMdmModuleDb.dbName
      this.formRow = []
      this.baseFormRowDispose(res.attribute.mainMdmModuleDb.sublistMdmModuleDbFileds, this.formRow)
//子表处理
      this.dialogTabaleInfo = []
      res.attribute.sublistMdmModuleDb.forEach(table => {
        table.sublistMdmModuleDbFileds.forEach(item => {
          item.mdmModuleDbFiledsRules.forEach(ele => {
            item[ele.ruleCode] = ele.ruleValue
            item['id'] = item.enName
          })
        })
        table.tableData = {}
        table.detailFields = []
        let tempObj = {
          tableData: [{}],
          detailFields: deepClone(table.sublistMdmModuleDbFileds),
          title: table.remark,
          name: table.dbName,
        }
        this.dialogTabaleInfo.push({...tempObj})
      })
//初始化数据
      const data = await getUserModuleApi({
        tl: "mdmService",
        as: "mdmService",
        dj: "queryMdmShowDetailsData",
      }, {
        mdmCode: this.$route.meta.mdmCode,
        id: id
      })
      if (data.status === '200') {
        this.ruleForm = data.attribute[this.mainTableName]
        this.dialogTabaleInfo.forEach(table => {
          table.tableData = []
          table.tableData = data.attribute[table.name]
          table.tableData.push({})
        })
      }
      this.dialogShow = true
    },
//查看dialog处理事件
    async viewDIalogHandle(id) {
      this.newFlag = false
      this.lookFlag = true
      //初始化模版
      const res = await getUserModuleApi({
        tl: "mdmService",
        as: "mdmService",
        dj: "queryMdmShowDetails"
      }, {
        mdmCode: this.$route.meta.mdmCode,
        showType: "5"
      })
      res.attribute.mainMdmModuleDb.sublistMdmModuleDbFileds.forEach(item => {
        item.mdmModuleDbFiledsRules.forEach(ele => {
          if (ele.ruleCode === "required" || ele.ruleCode === "disabled") {
            if (!ele.ruleValue) {
              item[ele.ruleCode] = false
            } else {
              item[ele.ruleCode] = JSON.parse(ele.ruleValue)
            }
          } else {
            item[ele.ruleCode] = ele.ruleValue
          }
          item['id'] = item.enName
        })
      })
      this.dialogFormName = res.attribute.mainMdmModuleDb.dbName
      this.formRow = []
      this.baseFormRowDispose(res.attribute.mainMdmModuleDb.sublistMdmModuleDbFileds, this.formRow)
      //子表处理
      this.dialogTabaleInfo = []
      res.attribute.sublistMdmModuleDb.forEach(table => {
        table.sublistMdmModuleDbFileds.forEach(item => {
          item.mdmModuleDbFiledsRules && item.mdmModuleDbFiledsRules.forEach(ele => {
            item[ele.ruleCode] = ele.ruleValue
            item['id'] = item.enName
          })
        })
        table.tableData = {}
        table.detailFields = []
        let tempObj = {
          tableData: [{}],
          detailFields: deepClone(table.sublistMdmModuleDbFileds),
          title: table.remark,
          name: table.dbName,
        }
        this.dialogTabaleInfo.push({...tempObj})
      })
      //初始化数据
      const data = await getUserModuleApi({
        tl: "mdmService",
        as: "mdmService",
        dj: "queryMdmShowDetailsData",
      }, {
        mdmCode: this.$route.meta.mdmCode,
        id: id
      })
      if (data.status === '200') {
        this.ruleForm = data.attribute[this.mainTableName]
        this.dialogTabaleInfo.forEach(table => {
          table.tableData = []
          table.tableData = data.attribute[table.name] || []
        })
      }
      this.dialogShow = true
    }
    ,
//删除此行
    async deleRowHanlde(id) {
      const res = await getUserModuleApi({
        tl: "mdmService",
        as: "mdmService",
        dj: "deleteMdmShowDetailsData",
      }, {
        mdmCode: this.$route.meta.mdmCode,
        id: id
      })
      if (res.status === '200') {
        this.$vmNews("删除成功！", "success")
        this.searchHandle()
        this.initTree(this.treeObj.label, this.treeObj.upId)
      }
    }
    ,
    homeHandleNodeClick(data) {
      let arrId = []
      arrId.push(data.id)
      if (data.children) {
        this.treeIdHandle(data.children, arrId)
      }
      this.pageModel.pageIndex = 1;
      this.pageModel.total = 0;
      this.pageModel.limit = 10;
      this.searchForm = {};
      this.tableData = [];
      this.lookFlag = false;
      this.newFlag = false;
      this.treeActiveRow = {...data, arrId: arrId}
      this.searchHandle()
    }
    ,
    //树点击
    treeIdHandle(data, arr) {
      data.forEach(item => {
        arr.push(item.id)
        if (item.children) {
          this.treeIdHandle(item.children, arr)
        }
      })
    },
    //下发方法
    async sendHandle(id) {
      const res = await getUserModuleApi({
        tl: "mdmService",
        as: "mdmService",
        dj: "queryMdmShowDistribute"
      }, {
        mdmCode: this.$route.meta.mdmCode,
        id: id
      })
      this.sendTableData = res.attribute
      this.sendTableData.forEach(item => {
        this.$set(item, 'rowId', id)
        this.appSearch(item.appId, item)
      })
      this.sendShow = true
    },
    //应用名查找
    async appSearch(id, row) {
      const res = await getUserModuleApi({
        tl: "sysApplicationService",
        as: "application",
        dj: 'getApp'
      }, {
        id: id
      })
      this.$set(row, 'name', res.attribute.name)
    },
    //下发dialog行按钮
    async sendRowHandle(row) {
      let status = row.status === '1' ? 1 : 2
      if (row.status === '2') {
        this.$vmNews("发送中，请等待发送完成，再删除", 'warning')
        return
      }
      console.log(row)
      const res = await getUserModuleApi({
        tl: "mdmService",
        as: "mdmService",
        dj: "doMdmDistribute",
      }, {
        mdmCode: this.$route.meta.mdmCode,
        appID: row.appId,
        id: row.rowId,
        dataType: status
      })
      this.$vmNews(`${res.msg}`, 'success')
      this.sendHandle(row.rowId)
    },
  },
  created() {
    this.init()
  }
  ,
  components: {
    BaseMenuTree,
    BaseTableForm,
    BasePage,
    BaseTable,
    BaseNewForm,
    baseDialog
  }
  ,
  computed: {
    funWidth() {
      return this.mainFunData.length * 70;
    }
    ,
  }
  ,
  watch: {
    $route(to) {
      this.init()
    }
  }
}
</script>

<style scoped lang="scss">
.wrap {
  display: flex;
  background-color: #fafafa;

  .tree {
    margin-right: 15px;
    background-color: #fff;
    border-radius: 8px;
    overflow: auto;
  }

  .main {
    overflow: auto;

    .top {
      padding: 20px;
      background-color: #fff;
      border-radius: 8px;

      > .btnList {
        display: flex;
        justify-content: flex-end;

        > .btnItem {
          margin-right: 15px;
        }
      }
    }

    .table {
      background-color: #fff;
      border-radius: 8px;
      margin-top: 15px;
      padding: 15px;

      > .nextPage {
        margin-top: 20px;
      }
    }

  }
}

.sonTable {
  border: 1px #cccccc dashed;
  padding: 5px 15px;
  margin-bottom: 5px;
  border-radius: 8px;
}
</style>

