<template>
  <div class="boxswai">
    <div class="boxnei">
      <el-row
        :gutter="20"
        style="height:100%;"
      >
        <el-col
          :span="5"
          style="height:99%;"
        >
          <div
            style="fontSize:18px; font-weight: 900;"
            class="marbottom5"
          >元素识别</div>

          <div style="height:98%;overflow: auto;width:auto;">
            <div class="flex">
              <el-input
                size="small"
                placeholder="输入关键字搜索"
                clearable
                @clear="allTreeShow = false"
                v-model="filterText">
              </el-input>
              <el-button size="small" class="mg-l-10" @click="treeFilter">搜索</el-button>
            </div>

            <el-tree
              :data="treeData"
              :props="treeProps"
              @node-click="handleNodeClick"
              :load="loadNode"
              :expand-on-click-node="false"
              lazy
              v-show="!allTreeShow"
            ></el-tree>

            <el-tree
              style="width:100%;"
              ref="treeall"
              v-loading="treeloading"
              :data="allTreeData"
              :props="treeProps"
              @node-click="handleNodeClick"
              node-key="id"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              v-show="allTreeShow"
            >
            </el-tree>
          </div>
        </el-col>
        <el-col
          :span="19"
          style="height:98%;"
        >
          <div v-if="addElementForm.deptName==''">表名称</div>
          <div v-else>{{addElementForm.deptName}}</div>
          <el-row
            class="martop20"
            :gutter="20"
            style="height:96%;"
          >
            <el-col
              :span="16"
              style="overflow:auto;height:100%;border:1px solid black; border-radius: 4px;box-sizing: border-box;padding: 10px 10px;"
            >
              <div
                class="parent"
                id='parent'
              >
              </div>
            </el-col>
            <el-col
              :span="8"
              style="overflow:auto;height:100%;"
            >
              <div class="flexBetween flexItemsC">
                <el-button
                  type="info"
                  size="mini"
                  :disabled="from.id==''"
                  @click="automaticRecognition"
                >自动识别</el-button>
                <div
                  class="el-icon-plus"
                  @click="pushTableData"
                  style="width:16px;height:16px;backgroundColor:#1DD81D;color:#fff;cursor: pointer;"
                ></div>
              </div>
              <el-table
                class="martop20"
                :data="tableData"
                border
                style="width: 100%"
              >
                <el-table-column
                  type="index"
                  label="坐标"
                >
                </el-table-column>
                <el-table-column
                  prop="eName"
                  label="元素名称"
                >
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.eName"
                      placeholder="请输入内容"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="eType"
                  label="数据类型"
                >
                  <template slot-scope="scope">
                    <el-select
                      v-model="scope.row.eType"
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="item in dataType"
                        :key="item.dictKey"
                        :label="item.dictValue"
                        :value="item.dictKey"
                      >
                      </el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="eAllowDeviation"
                  label="允许偏差值"
                >
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.eAllowDeviation"
                      placeholder="请输入内容"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-link
                      type="danger"
                      @click="deleteTableData(scope.$index)"
                    >删除</el-link>
                  </template>
                </el-table-column>
              </el-table>
              <el-button
                type="success"
                class="martop20 dingwei"
                @click="establish()"
                :disabled="from.id==''"
              >关联WBS并创建元素</el-button>
            </el-col>
          </el-row>
        </el-col>
      </el-row>

      <!-- 关联公共WBS模板 -->
      <el-dialog
        title="关联公共WBS模板"
        class="excelBox"
        :visible.sync="AssociatedPublicTap"
        modal-append-to-body
        append-to-body
        :before-close="AssociatedPublicClose"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-select
              style="width:100%;"
              v-model="GLExcelFrom.name"
              placeholder="请选择"
              @change="changetherr()"
            >
              <el-option
                v-for="(item,key) in GLExcelData"
                :key="key"
                :label="item.wbsName"
                :value="item.id"
              >
              </el-option>
            </el-select>
            <el-scrollbar style="height:50vh;">
              <el-tree
                v-if="GLExcelFromtag"
                @node-click="handleNodeClickExcel"
                ref="tree"
                class="filter-tree"
                style="margin-top:10px;"
                :props="GLExcelProps"
                :data="exceldata"
                :load="loadNodeTan"
                lazy
                node-key="id"
                accordion
                :show-checkbox="activeName == 'add'"
                :check-strictly="true"
              >
              </el-tree>
            </el-scrollbar>
          </el-col>
          <el-col
            :span="12"
            v-if="addElementForm.wbsId"
          >
             <el-tabs v-model="activeName" type="card" >
              <el-tab-pane label="关联元素表" name="link">
                <el-table
                  :data="addTableData"
                  border
                  style="width: 100%"
                  class="martop20"
                >
                  <el-table-column
                    prop="tableName"
                    label="已有元素表名称"
                    align="center"
                  >
                  </el-table-column>
                  <el-table-column
                    prop="name"
                    label="操作"
                    align="center"
                  >
                    <template slot-scope="scope">
                      <el-button
                        type="primary"
                        size="mini"
                        style="margin:0px;"
                        @click="relationMD(scope.row,'关联')"
                        v-show="!scope.row.checknd"
                        :loading="scope.row.loading"
                      >选择关联</el-button>
                      <el-button
                        type="danger"
                        size="mini"
                        style="margin:0px;"
                        @click="relationMD(scope.row,'取消关联')"
                        v-show="scope.row.checknd"
                        :loading="scope.row.loading"
                      >取消关联</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-tab-pane>
              <el-tab-pane label="新增元素表" name="add">
                <div>
                  <div class="flexBetween martop20">
                    <el-input
                      v-model="addElementForm.deptName"
                      placeholder="请输入表名"
                    ></el-input>
                    <el-select
                      class="marleft10"
                      v-model="addElementForm.tableType"
                      placeholder="请选择表类型"
                    >
                      <el-option
                        v-for="(item,index) in  exceltypeData"
                        :key="index"
                        :label="item.dictValue"
                        :value="item.dictKey"
                      ></el-option>
                    </el-select>
                  </div>
                  <el-select
                    style="width:100%;"
                    class="martop20"
                    v-model="addElementForm.tableOwner"
                    placeholder="请选择所属方"
                  >
                    <el-option
                      v-for="(item,index) in ownerTypeList"
                      :key="index"
                      :label="item.dictValue"
                      :value="item.dictKey"
                    ></el-option>
                  </el-select>
                </div>
              </el-tab-pane>
            </el-tabs>
          </el-col>
        </el-row>
        <span
          slot="footer"
          class="dialog-footer"
          style="display: flex;justify-content: center;align-items: center;"
        >
          <el-button @click="AssociatedPublicClose()">取 消</el-button>
          <el-button
            style="margin-left:30px;"
            type="primary"
            @click="saveElementMD()"
          >确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { tabLazytree, getExcelHtmlCol, excelType, submitExcelRelationWbsTreeAndElement, getWbsTypeList, getLazytree,cancelRelation,saveRelation,searchNodeTables,tabLazytreeAll} from "@/api/exctab/excelmodel";
import { dictionarydataType } from "@/api/exctab/editelement";
import { getColByTabId } from "@/api/manager/AdjustForm";
import { selectByNodeTable } from "@/api/manager/wbstree";
import { getDictionary } from "@/api/system/dict";
import Vue from 'vue'
export default {
  data () {
    return {
      //#region 左侧树节点
      treeData: [],
      treeProps: {
        label: 'name',
        children: 'children',
        isLeaf: 'hasChildren'
      },
      //#endregion
      excelSrc: '',
      from: {
        id: '',
      },
      tableData: [],//外层table
      dataType: [],
      filterText:"",//搜索关键字
      allTreeShow:false,//是否显示整棵树
      treeloading:false,
      AssociatedPublicTap: false,
      //#region 弹框属性
      GLExcelFrom: {
        id: "",
        name: '',
        search: '',//搜素框舒服的值
      },
      GLExcelData: [],//
      allTreeData:[],
      GLExcelProps: {
        label: 'title',
        children: 'children',
        isLeaf: function (data) {
          if (data.hasChildren && data.isExistForm != 1) {
            return false
          } else if (data.hasChildren && data.isExistForm == 1) {
            return true
          } else {
            return true
          }
        }
      },
      exceldata: [],//清表模板树数据
      addTableData: [],//新增元素信息表
      exceltypeData: [],//清表类型
      addElement: false,
      GLExcelFromtag: false,
      addElementForm: {
        id: "",
        initTableName: "",
        deptName: '',
        tableType: '',
        tableOwner: '',
        wbsId: '',
        parentId: '',
      },
      //#endregion

      ownerTypeList: [],

      activeName:'link',
    }
  },
  methods: {

    //搜索树
    treeFilter(){
      if(this.filterText){
        this.allTreeShow = true;
        if(!this.allTreeData.length){
          this.treeloading = true;
          tabLazytreeAll({
            modeId: this.$route.params.id,
            name:'',
          }).then((res)=>{
            this.treeloading = false;
            this.allTreeData = res.data.data;
            this.$nextTick(()=>{
              this.$refs.treeall.filter(this.filterText);
            })
          })
        }else{
          this.$refs.treeall.filter(this.filterText);
        }
      }else{
        this.allTreeShow = false;
      }
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    //#region
    handleNodeClick (data) {//树节点点击事件
      console.log(data);
      if (data.fileType == 3) {
        this.getExcelHtmlCol(data.id)//获取excel模板
        if (this.dataType.length == 0) {
          this.dictionarydataType() //数据类型字典
        }
        this.addElement = false
        this.addElementForm.deptName = data.name
        this.from.id = data.id

        this.tableData = [];
      }
    },
    async loadNode (node, resolve) {//懒加载获取节点
      if (node.level === 0) {
        return resolve(await this.tabLazytree(this.$route.params.id, 0))
      }
      if (node.level > 0) {
        return resolve(await this.tabLazytree(this.$route.params.id, node.data.id))
      }
    },
    automaticRecognition () {//自动识别按钮
      this.getColByTabId()
    },
    pushTableData () {//
      if (this.from.id) {
        this.tableData.push({
          eName: '',
          eType: 1,
          eAllowDeviation: ''
        })
      }
    },
    deleteTableData (key) {//删除
      this.tableData.splice(key, 1)
    },
    async getColByTabId () {//获取字段信息
      const { data: res } = await getColByTabId({ tabId: this.from.id })
      console.log(res);
      if (res.code === 200) {
        res.data.forEach((element)=>{
          element.eName = element.textInfo;
          element.eType = 1;
        })
        this.tableData = res.data
      }
    },
    async getExcelHtmlCol (id) {//获取excel模板
      const { data: res } = await getExcelHtmlCol({ id })
      console.log(res);
      if (res.code == 200) {
        // let _that = this
        var MyComponent = await Vue.extend({
          data () {
            return {
              formData: {}
            }
          },
          template: res.data,
        })
        var component = new MyComponent().$mount()
        let na = document.getElementById('parent')
        na.innerHTML = `<div
        class='parent'
        id='parent'"
      ></div>`
        document.getElementById('parent').appendChild(component.$el);
      }
    },
    //#endregion

    //#region 关联公共WBS模板弹框
    establish () {//关联WBS并创建元素
      if(this.tableData.length == 0){
        this.$message({
          type: 'warning',
          message: '至少有一条元素才能创建元素表'
        })
        return;
      }
      let arr = [];
      this.tableData.forEach((element,index)=>{
        if(element.eName == ''){
          arr.push(index+1);
        }
      })
      if(arr.length > 0){
        this.$message({
          type: 'warning',
          message: arr.join(',')+'条的元素名称未填写'
        })
        return;
      }

      this.getWbsTypeList()
      this.AssociatedPublicTap = true
    },
    AssociatedPublicClose () {//关联公共WBS模板关闭事件
      // this.addElementForm = {
      //   id: "",
      //   initTableName: "",
      //   deptName: this.addElementForm.deptName,
      //   tableType: '',
      //   tableOwner: '',
      //   wbsId: '',
      //   parentId: '',
      // }
      // this.GLExcelFrom = {
      //   name: '',
      //   search: ''
      // }
      // this.exceldata = []
      // this.addElement = false
      this.addTableData = []
      this.AssociatedPublicTap = false
    },
    async loadNodeTan (node, resolve) {//懒加载
      console.log(node);
      if (node.level === 0) {
        return resolve(await this.getLazytree(0));
      } else {
        return resolve(await this.getLazytree(node.data.id));
      }
    },
    changetherr () {//下拉框change事件
      this.GLExcelFromtag = false
      if (this.GLExcelFrom.name != "") {
        this.GLExcelFrom.search = ''
        this.exceldata = []
        this.addTableData = []
        this.addElementForm.wbsId = ''
        this.$nextTick(() => {
          this.GLExcelFromtag = true
        })
      }
    },
    addElementMD () {//新增元素信息表按钮
      this.excelType()
      this.addElement = true
    },
    async getWbsTypeList () {//获取清表模板信息
      const { data: res } = await getWbsTypeList({ wbstype: 1 })
      console.log(res);
      if (res.code === 200 && res.msg === '操作成功') {
        this.GLExcelData = res.data
      }
    },
    async getLazytree (parentId) {//清表树信息
      const { data: res } = await getLazytree({
        parentId: parentId,
        wbsId: this.GLExcelFrom.name,
        wbsType: '1'
      })
      console.log(res);
      if (res.code === 200 && res.msg === '操作成功') {
        res.data.forEach(val => {
          val.isExistForm = !!val.isExistForm
        })
        return res.data
      } else {
        return []
      }
    },
    handleNodeClickExcel (data) {//点击节点事件
      this.addElementForm.wbsId = this.GLExcelFrom.name
      this.addElementForm.parentId = data.id
      //this.selectByNodeTable(data.id)
      this.searchNodeTables(data.id)
    },
    async selectByNodeTable (id) {//获取清表信息
      const { data: res } = await selectByNodeTable(id)
      console.log(res);
      if (res.code == 200) {
        if (res.data.length > 0) {
          res.data.forEach(val => {
            if (val.isLinkTable == 2) {
              val.checknd = true
            } else {
              val.checknd = false
            }
            val.loading = false;
          })
          this.addTableData = res.data
        }else{
          this.addTableData = []
        }

      }
    },

    //查看节点下已关联的元素表信息
    searchNodeTables(id){
      searchNodeTables(id,this.from.id).then((res)=>{
        if (res.data.data.length > 0) {
          res.data.data.forEach(val => {
            if (val.isLinkTable == 2) {
              val.checknd = true
            } else {
              val.checknd = false
            }
            val.loading = false;
          })
          this.addTableData = res.data.data
        }else{
          this.addTableData = []
        }
      })
    },

    async excelType () {//清表类型
      const { data: res } = await excelType({ code: 'sys_excltab_type' })
      console.log(res);
      if (res.code === 200) {
        this.exceltypeData = res.data
      }
    },
    relationMD (row, type) {//关联取消关联
      row.loading = true;
      if (type == '关联') {
        saveRelation(row.id,this.from.id,this.tableData).then(()=>{
          row.checknd = true;
          row.isLinkTable = 2;
        }).finally(()=>{
          row.loading = false;
        })

      } else {
        cancelRelation({
          id:row.id,
          excelTabId:this.from.id,
        }).then(()=>{
          row.checknd = false;
          row.isLinkTable = 1;
        }).finally(()=>{
          row.loading = false;
        })
      }
    },
    saveElementMD () {//保存按钮
      if (this.addElementForm.wbsId) {
        if (this.activeName == 'link') {

          this.submitExcelRelationWbsTreeAndElement({
            excelTabId:this.from.id,
            elementList: this.tableData,
            submitStatus:1
          })
        } else {
          if (this.addElementForm.deptName && this.addElementForm.tableType && this.addElementForm.tableOwner) {
            let nodeIds = this.$refs.tree.getCheckedKeys();
            if(nodeIds.length < 1){
              this.$message({
                type: 'warning',
                message: '至少勾选一个节点'
              })
              return;
            }

            this.submitExcelRelationWbsTreeAndElement({
              deptName: this.addElementForm.deptName,
              tableType: this.addElementForm.tableType,
              tableOwner: this.addElementForm.tableOwner,
              wbsId: this.addElementForm.wbsId,
              elementList: this.tableData,
              nodeIds:nodeIds,
              excelTabId:this.from.id,
              submitStatus:2
            })
          }else{
            this.$message({
              type: 'warning',
              message: '请填写和选择新增的表名，表类型，表所属方'
            })
          }
        }
      } else {
        this.$message({
          type: 'warning',
          message: '请先选择WBS树节点表单'
        })
      }
    },
    async submitExcelRelationWbsTreeAndElement (da) {//保存接口
      const { data: res } = await submitExcelRelationWbsTreeAndElement(da)
      console.log(res);
      if (res.code == 200) {
        this.$message({
          type: 'success',
          message: '设置成功'
        })
        this.AssociatedPublicTap = false
      }
    },
    //#endregion

    //#region 接口
    async tabLazytree (modeId, parentId) {
      const { data: res } = await tabLazytree({ modeId, parentId })
      console.log(res);
      if (res.code == 200) {
        if (res.data.length > 0) {
          res.data.forEach(val => {
            val.hasChildren = !val.hasChildren
          });
        }
        return res.data
      }
    },
    async dictionarydataType () {//数据类型字典
      const { data: res } = await dictionarydataType()
      console.log(res);
      if (res.code == 200) {
        res.data.forEach(element => {
          element.dictKey = Number(element.dictKey)
        });
        this.dataType = res.data
      }
    },
    //#endregion

    getOwnerTypelist () {
      if (this.ownerTypeList.length > 1) {
        return;
      }
      getDictionary({
        code: 'owner_type'
      }).then((res) => {
        res.data.data.forEach(element => {
          element.dictKey = Number(element.dictKey)
        });
        this.ownerTypeList = res.data.data;
      })
    },
  },
  created () {
    this.getOwnerTypelist();
    this.excelType();
  }
}
</script>

<style lang="scss" scoped>
.boxswai {
  padding: 0px 14px 10px 14px !important;
}
.dingwei {
  position: fixed;
  bottom: 40px;
  right: 40px;
}
//树结构超长后产生滚动条
.el-tree > .el-tree-node {
  min-width: 100%;
  display: inline-block;
}
</style>
