<template>
  <div>
    <div class="box flexBetween">
      <!-- 左侧树结构 -->
      <div :style="{'width':threessW+'px'}">
        <div
          class="box flexStar"
          style="width:100%;"
        >
          <el-scrollbar style="width:100%;">
            <basic-container style="width:100%;">
              <!-- 树结构 -->
              <avue-tree
                style="width:100%;"
                :permission="getPermission"
                :loading="loading"
                :option="option"
                :data="data"
                @node-click="nodeClick"
              >
                <span
                  class="el-tree-node__label"
                  slot-scope="{ data }"
                >
                  <div>
                    <span style="text-overflow: ellipsis;width:70%;"> {{ data.name }} </span>
                    <!-- <span> {{ node}} </span> -->
                    <!-- 添加 -->
                    <i
                      class="el-icon-circle-plus-outline marleft10"
                      @click.stop="addExcel(data)"
                      v-if="data.fileType!=3"
                    ></i>
                    <!-- 编辑 -->
                    <i
                      class="el-icon-edit marleft10"
                      @click.stop="editExcel(data)"
                      v-if="data.fileType!=1"
                    ></i>
                    <!-- 删除 -->
                    <i
                      class="el-icon-delete marleft10"
                      @click.stop="deleteExcelM(data)"
                      v-if="!data.hasChildren&&data.fileType!=1"
                    ></i>
                  </div>
                </span>
              </avue-tree>
            </basic-container>
          </el-scrollbar>
          <div
            style="border-left:5px solid rgba(255,255,255,0);position:relative;left: -6px;z-index:999"
            @mousedown="mousedown1()"
          ></div>
        </div>
      </div>
      <!-- 右侧 -->
      <div class="rightBox box">
        <el-scrollbar>
          <basic-container>
            <!-- 上传、删除、下载操作栏 -->
            <div
              class="rightHeader"
              v-show="from.checkd&&from.fileUrl"
            >
              <div class="excelname">
                <div>{{from.extension}}</div>
                <i
                  class="el-icon-success marleft10"
                  style="color: rgb(0, 168, 112);"
                ></i>
              </div>
              <el-upload
                class="marleft10"
                :auto-upload="false"
                :show-file-list="false"
                action="#"
                :limit="1"
                :file-list='fileList'
                accept=".xls,.xlsx"
                :on-change="uploadChange"
              >
                <el-button
                  type="primary"
                  size="mini"
                >重新上传</el-button>
              </el-upload>
              <el-link
                class="marleft10 colorblue"
                @click="delectExcelMS"
              >删除</el-link>
              <el-link
                underline
                class="marleft10 colorblue"
                style="text-decoration:underline;"
                @click="downloadExcel()"
              >下载EXCEL</el-link>
            </div>
            <div
              class="rightHeader"
              v-show="from.checkd&&!from.fileUrl"
            >
              <el-upload
                :auto-upload="false"
                :show-file-list="false"
                action="#"
                :limit="1"
                :file-list='fileList'
                accept=".xls,.xlsx"
                :on-change="uploadChange"
              >
                <el-button
                  type="primary"
                  size="mini"
                >上传 excel</el-button>
              </el-upload>
            </div>
            <el-empty
              v-show="!from.checkd"
              description="该目录为根目录没有EXCEL文件"
            ></el-empty>
            <div
              style="height:700px;margin-top:20px;"
              v-if="from.fileUrl"
            >
              <iframe
                :src="excelSrc"
                width="100%"
                height="100%"
              ></iframe>
            </div>
          </basic-container>
        </el-scrollbar>
      </div>
    </div>

    <!-- 弹出框 -->
    <el-dialog
      :title="dialogTapType"
      class="dialogModel"
      :visible.sync="dialogTap"
      width="800px"
      modal-append-to-body
      append-to-body
      :before-close="handleClose"
    >
      <div class="dialogBox">
        <el-form
          ref="excelForm"
          :model="excelForm"
          label-width="80px"
          rules="rules"
        >
          <div style="display: flex;justify-content: space-between;">
            <el-form-item
              label="清表名称"
              style="width: 370px;"
              size="small"
              prop="nodeName"
            >
              <el-input v-model="excelForm.nodeName"></el-input>
            </el-form-item>
            <el-form-item
              label="清表类型"
              style="width: 370px;"
              size="small"
              prop="tabType"
            >
              <el-select
                v-model="excelForm.tabType"
                style="width:100%;"
                placeholder="请选择清表类型"
              >
                <el-option
                  v-for="(val,index) in exceltypeData"
                  :key="index"
                  :label="val.dictValue"
                  :value="val.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
        </el-form>
        <div
          class="middle"
          v-if="wbsmiddle"
        >
          <div class="left">
            <div class="select">
              <el-select
                placeholder="请选择WBS模板"
                style="width: 96%;"
                size="small"
                @change="wbsmodelchange"
                v-model="excelForm.wbsId"
              >
                <el-option
                  v-for="(val,index) in wbsmodel"
                  :key="index"
                  :label="val.wbsName"
                  :value="val.id"
                ></el-option>
              </el-select>
            </div>
            <div class="leftscroll">
              <avue-tree
                :permission="getPermission"
                :loading="loading"
                :option="option2"
                :data="wbsdata"
                @node-click="nodeClickExcel"
              >
                <span
                  class="el-tree-node__label"
                  slot-scope="{ data }"
                >
                  <div>
                    <span> {{ data.deptName }} </span>
                  </div>
                </span>
              </avue-tree>
            </div>
          </div>
          <!-- 右侧关联 -->
          <template>
            <table
              class="right"
              width="49%"
              bordercolor="#DCDCDC"
              border="1px"
            >
              <thead>
                <tr>
                  <td>表名</td>
                  <td>操作</td>
                </tr>
              </thead>
              <tbody>
                <tr
                  v-for="(val,index) in tableData"
                  :key="index"
                >
                  <td style="width:50%;">{{val.tableName}}</td>
                  <td style="text-align: center;height:30px;">
                    <el-button
                      v-if="val.isLinkTable!=2"
                      type="info"
                      size="small"
                      @click="relation(index)"
                    >关联</el-button>
                    <el-button
                      v-if="val.isLinkTable==2"
                      type="warning"
                      size="small"
                      @click="Disassociate(index)"
                    >取消关联</el-button>
                  </td>
                </tr>
              </tbody>
            </table>
          </template>
        </div>
      </div>
      <div class="btbox">
        <el-button
          size="mini"
          @click="handleClose()"
        >取消</el-button>
        <el-button
          type="info"
          style="margin-left: 50px;"
          size="mini"
          @click="saveExcel()"
        >确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { detailExcel, excelType, tabLazytree, getWbsTypeList, wbstree, selectByNodeTable, Excelmodify, uploadExcel, deleteExcelshu, deleteExcel } from '@/api/exctab/excelmodel'
export default {
  data () {
    return {
      //#region 鼠标
      threessW: 400,
      tharrss: true,
      mouse1: {
        x: '',
        y: '',
      },//开始
      mouse2: {
        x: '',
        y: '',
      },//结束
      //#endregion

      loading: false,//懒加载
      option: {
        filter: false,
        lazy: true,
        treeLoad: (async (node, resolve) => {
          console.log(node);
          console.log(resolve);
          if (node.data.hasChildren) {
            const { data: res } = await tabLazytree({ parentId: node.data.id, modeId: this.$route.params.id })
            console.log(res);
            if (res.code === 200) {
              if (Array.isArray(res.data)) {
                res.data.forEach((val) => {
                  if (!val.hasChildren) {
                    val.leaf = true
                  }
                })
              }
              return resolve(res.data)
            }
          } else {
            return resolve([])
          }
        }),
      },
      data: [],//清表模板
      wbsdata: [],//wbs模板
      //#region 右侧数据
      from: {
        checkd: false,//判断是否可以进行上传、重新上传excel
        id: '',//清表树ID
        extension: '', //文件名称
        fileUrl: '',//文件路径
      },
      fileList: [],//选中的文件
      excelSrc: '',//
      //#endregion

      //#region   弹框
      dialogTapType: '',
      dialogTap: false,
      option2: {
        filter: false,
        lazy: true,
        treeLoad: (async (node, resolve) => {
          if (node.data.hasChildren) {
            const { data: res } = await wbstree({ parentId: node.data.id, wbsId: this.excelForm.wbsId, wbsType: this.excelForm.wbsType })
            console.log(res);
            if (res.code === 200) {
              if (Array.isArray(res.data)) {
                res.data.forEach((val) => {
                  if (!val.hasChildren) {
                    val.leaf = true
                  }
                })
              }
              return resolve(res.data)
            }
          } else {
            return resolve([])
          }
        }),
      },//弹框里面的wbs树
      excelForm: {
        nodeName: '',//清表名称
        tabType: '',//清表类型
        id: '',//清表Id,编辑时用
        parentId: '',//清表Id，添加时用
        wbsId: '',//WBS模板Id
        wbsType: '',//WBS模板类型
      },
      rules: {
        nodeName: [
          { required: true, message: '请输入清表名称', trigger: 'blur' },
        ],
        tabType: [
          { required: true, message: '请选择清表类型', trigger: 'blur' },
        ],
      },
      wbsform: {
        id: '',
        wbsType: '',
        wbsName: '',
      },//wbs树选中的值
      tableData: [],//右侧表数据
      wbsmiddle: false,//选择wbs模板那块是否有
      tableList: [],//进行处理的wbs关联表
      exceltypeData: [],//清表类型枚举
      wbsmodel: [],//wbs模板名称枚举
      //#endregion
    }
  },
  methods: {
    //#region 接口
    async tabLazytree (parentId, modeId) {//清表树
      const { data: res } = await tabLazytree({ parentId, modeId })
      console.log(res);
      if (res.code === 200) {
        if (Array.isArray(res.data)) {
          res.data.forEach((val) => {
            if (!val.hasChildren) {
              val.leaf = true
            }
          })
        }
        this.data = res.data
      }
    },
    async detailExcel (id) {//获取列表信息
      const { data: res } = await detailExcel({ id })
      console.log(res);
      if (res.code === 200) {
        this.from.id = res.data.id
        this.from.extension = res.data.extension  //文件名称
        this.from.fileUrl = res.data.fileUrl      //文件路径
        let routeUrl = res.data.fileUrl
        let pSrc = routeUrl + '?r=' + new Date()
        this.excelSrc = 'http://view.officeapps.live.com/op/view.aspx?src=' + encodeURIComponent(pSrc)
      }
    },
    async getWbsTypeList () {//清表编辑 wbs 下拉框选择
      const { data: res } = await getWbsTypeList({ wbstype: 2 })
      console.log(res);
      if (res.code === 200) {
        this.wbsmodel = res.data
      }
    },
    async excelType () {//清表类型
      const { data: res } = await excelType({ code: 'sys_excltab_type' })
      console.log(res);
      if (res.code === 200) {
        this.exceltypeData = res.data
      }
    },
    async wbstree () {//wbs树懒加载
      const { data: res } = await wbstree({ parentId: 0, wbsId: this.excelForm.wbsId, wbsType: this.excelForm.wbsType })
      console.log(res);
      if (res.code === 200) {
        res.data.forEach((val) => {
          if (!val.hasChildren) {
            val.leaf = true
          }
        })
        this.wbsdata = res.data
      }
    },
    async selectByNodeTable (id, wbsType, projectid) {//wbs树获取表
      const { data: res } = await selectByNodeTable({ id, wbsType, projectid })
      console.log(res);
      if (res.code === 200) {
        console.log(Array.isArray(res.data));
        if (Array.isArray(res.data)) {
          this.tableData = res.data
          this.tableData.forEach(val => {
            val.changeTable = val.isLinkTable
          })
        } else {
          this.tableData = []
        }
      }
    },
    async deleteExcelshu (ids) {//删除清表
      // console.log(ids);
      const { data: res } = await deleteExcelshu(ids)
      console.log(res);
      if (res.code === 200) {
        this.$message({
          message: '删除清表树成功',
          type: 'success'
        });
        this.tabLazytree(0, this.$route.params.id)//获取清表树
        this.from = {
          checkd: false,//判断是否可以进行上传、重新上传excel
          id: '',//清表树ID
          extension: '', //文件名称
          fileUrl: '',//文件路径
        }
      }
    },
    async Excelmodify (wbsExclTabParmVO) {//编辑添加清表
      console.log(wbsExclTabParmVO);
      const { data: res } = await Excelmodify(wbsExclTabParmVO)
      console.log(res);
      if (res.code === 200) {
        await this.tabLazytree(0, this.$route.params.id)//获取清表树
        this.dialogTap = false
      }
    },
    async uploadExcel (data) {//上传清表
      const { data: res } = await uploadExcel(data)
      console.log(res);
      if (res.code === 200) {
        this.$message({
          message: '上传文件成功',
          type: 'success'
        })
        this.detailExcel(this.from.id)
      }
      this.fileList = []
    },
    async deleteExcel (data) {//删除excel表
      const { data: res } = await deleteExcel(data)
      if (res.code === 200) {
        this.$message({
          message: '删除excel表成功',
          type: 'success'
        })
        this.detailExcel(this.from.id)
      }
    },
    //#endregion

    //#region 右侧
    async uploadChange (file, fileList) {//选中表后触发
      console.log(file, fileList);
      this.fileList = [file.raw]
      let formData = new FormData()
      formData.append('file', ...this.fileList)
      formData.append('nodeId', this.from.id)
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      try {
        await this.uploadExcel(formData)
        loading.close();
      } catch (error) {
        loading.close();
      }
    },
    delectExcelMS () {//删除excel表点击事件、
      let _that = this
      this.$confirm('确认删除该文件?', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        _that.deleteExcel({ id: _that.from.id, fileUrl: '' })
      }).catch(() => {
      })
    },
    downloadExcel () {//下载excel表
      window.open(this.from.fileUrl)
    },
    //#endregion

    //#region  外层左侧事件
    nodeClick (data) {//外层树结构
      console.log(data);
      if (data.hasChildren == false || data.fileType == 3) {
        this.from.checkd = true
      } else {
        this.from.checkd = false
      }
      if (this.from.checkd) {
        this.detailExcel(data.id)
      } else {
        this.from = {
          checkd: false,//判断是否可以进行上传、重新上传excel
          id: '',//清表树ID
          extension: '', //文件名称
          fileUrl: '',//文件路径
        }
      }
    },
    async editExcel (data) {//编辑
      this.dialogTapType = '编辑'
      console.log(data);
      if (data.fileType != 3 && data.hasChildren) {
        this.wbsmiddle = false
      } else {
        this.wbsmiddle = true
        this.getWbsTypeList()//wbs模板名称
      }
      const { data: res } = await detailExcel({ id: data.id })
      console.log(res);
      if (res.code === 200) {
        this.excelForm.id = res.data.id
        this.excelForm.nodeName = res.data.name      //清表名称
        this.excelForm.tabType = res.data.tabType    //清表类型
        this.dialogTap = true
      }
    },
    async addExcel (data) {//添加
      this.dialogTapType = '新增'
      console.log(data);
      if (data.fileType == 3) {
        this.wbsmiddle = false
      } else {
        this.wbsmiddle = true
        this.getWbsTypeList()//wbs模板名称
      }
      this.excelForm.parentId = data.id
      this.dialogTap = true
    },
    deleteExcelM (data) {//删除
      const _that = this
      this.$confirm('确定将选择数据删除?', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        _that.deleteExcelshu(data.id)
      }).catch(() => {
      });
    },
    //#endregion

    //#region 弹框属性
    handleClose () {//关闭弹框触发事件
      this.excelForm = {
        nodeName: '',//清表名称
        tabType: '',//清表类型
        id: '',//清表Id,编辑时用
        parentId: '',//清表Id，添加时用
        wbsId: '',//WBS模板Id
        wbsType: '',//WBS模板类型
      }
      this.wbsform = {
        id: '',
        wbsType: '',
        wbsName: '',
      }//wbs树选中的值
      this.wbsdata = []  //wbs树数据
      this.tableData = []//弹框table数据
      this.tableList = []//关联取消关联的数据
      this.dialogTap = false
    },
    wbsmodelchange (val) {//wbs模板change事件
      if (val) {
        this.wbsmodel.forEach((da) => {
          if (da.id == val) {
            this.loading = true
            window.setTimeout(() => {
              this.excelForm.wbsType = da.wbsType
            }, 2000)
            this.loading = false
          }
        })
      }
      this.wbstree()
    },
    nodeClickExcel (data) {//wbs树点击事件
      console.log(data);
      this.wbsform.id = data.id
      this.wbsform.wbsType = data.type
      this.wbsform.wbsName = data.deptName
      if (this.tableList == '') {
        this.selectByNodeTable(data.id, data.type, this.excelForm.wbsId)
      } else {
        let tag = true
        this.tableList.forEach((val) => {
          if (val.id == data.id) {
            this.tableData = val.arrs
            tag = false
          }
        })
        if (tag) {
          this.selectByNodeTable(data.id, data.type, this.excelForm.wbsId)
        }
      }

    },
    relation (key) {//关联
      this.tableData[key].isLinkTable = 2
      let tap = this.tableList.find((val) => {
        return val.id == this.wbsform.id
      })
      if (!tap) {
        this.tableList.push({
          id: this.wbsform.id,
          wbsType: this.wbsform.wbsType,
          wbsName: this.wbsform.wbsName,
          arrs: this.tableData
        })
      }
    },
    Disassociate (key) {//取消关联
      this.tableData[key].isLinkTable = 1
      const tap = this.tableList.find((val) => {
        return val.id == this.wbsform.id
      })
      if (!tap) {
        this.tableList.push({
          id: this.wbsform.id,
          wbsType: this.wbsform.wbsType,
          wbsName: this.wbsform.wbsName,
          arrs: this.tableData
        })
      }
    },
    saveExcel () {//保存按钮
      this.$refs.excelForm.validate(async (valid) => {
        if (valid) {
          let linkDataInfo = []
          if (this.tableList.length > 0) {
            this.tableList.forEach(val => {
              let linkIds = ''
              val.arrs.forEach(da => {
                if (da.isLinkTable != da.changeTable) {
                  linkIds = `${linkIds}${linkIds != '' ? ',' : ''}${da.pkeyId}`
                }
              })
              if (linkIds != '') {
                linkDataInfo.push({
                  id: val.id,
                  linkIds: linkIds,
                  wbsName: val.wbsName,
                  wbsType: val.wbsType
                })
              }
            })
          }
          if (this.excelForm.parentId && !this.excelForm.id) {
            await this.Excelmodify({
              nodeName: this.excelForm.nodeName,
              tabType: this.excelForm.tabType,
              parentId: this.excelForm.parentId,
              linkDataInfo: linkDataInfo
            })
          } else {
            await this.Excelmodify({
              nodeName: this.excelForm.nodeName,
              tabType: this.excelForm.tabType,
              id: this.excelForm.id,
              linkDataInfo: linkDataInfo
            })
          }
          this.handleClose()
        }
      });
    },
    //#endregion

    //#region 树结构拉事件
    mousedown1 () {//鼠标按下事件
      document.onmousemove = (va) => {
        this.threessW = va.clientX - 240
      }
      document.onmouseup = () => {
        document.onmousemove = null;
        document.onmouseup = null;
      }
    },
    //#endregion
  },
  created () {
    this.excelType()//清表类型
    this.tabLazytree(0, this.$route.params.id)//获取清表树
  },
}
</script>

<style scoped lang="scss">
.marleft10 {
  margin-left: 10px;
}
/deep/.el-tree-node__expand-icon {
  font-size: 16px;
}
.colorblue {
  color: rgb(0, 82, 217);
}

.box {
  height: 800px;
}

.el-scrollbar {
  height: 100%;
}

.box .el-scrollbar__wrap {
  overflow: scroll;
}

.rightHeader {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  font-size: 14px;
  background-color: #fff;

  .excelname {
    box-sizing: border-box;
    min-width: 200px;
    height: 28px;
    border: 1px solid rgb(220, 220, 220);
    padding: 0 10px;
    border-radius: 3px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.dialogModel {
  .dialogBox {
    .middle {
      display: flex;

      .left {
        border: 1px solid rgb(220, 220, 220);
        border-radius: 3px;
        height: 500px;
        width: 49%;

        .select {
          box-sizing: border-box;
          display: flex;
          justify-content: center;
          padding: 5px 0;
          border-bottom: 1px solid #e0e0e0;
        }
        .leftscroll {
          height: 450px;
          overflow-y: scroll;
        }
      }

      .right {
        height: auto;
        height: 60px;
        max-height: 500px;
        margin-left: 2%;
        // height: 500px;
        border-radius: 3px;
        td {
          box-sizing: border-box;
          padding: 5px 10px;
          height: 30px;
          line-height: 30px;
        }
      }
    }
  }

  .btbox {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
}

.rightBox {
  flex: 1;
}
</style>
