<template>
  <div v-if="list.length > 0" class="diy-container">
    <el-tabs v-model="activeName">
      <el-tab-pane label="自定义模板" name="first">
        <div class="diy-wr">
          <div class="left">
            <el-tabs v-model="leftActive" tab-position="left" class="left-h" @tab-click="handleTabsClick">
              <el-tab-pane v-for="item in leftList" :key="item.id" :label="item.label" :name="item.id">
                <div class="pd10 check-boxwr scroll-h">
                  <checkBox v-if="item.queryItemList.length > 0" :ref="'checkbox' + item.id"
                  :list="item.queryItemList" @change="handleChangeBox" />
                </div>
              </el-tab-pane>

            </el-tabs>
          </div>
          <div class="right">
            <div class="right-header">
              <div class="title">导出信息</div>
              <el-button plain @click="handlePreview('')">预览</el-button>
            </div>
            <div class="h80 scroll-h">
              <el-collapse v-model="activeCollapse" id="collapsWr">
                <el-collapse-item v-for="item in rightList" :key="item.id"
                :title="item.label" :name="item.id" class="col-h">
                  <dragItem :ref="'drag' + item.id" :list="item.queryItemList" :id="item.id"
                  @del="handleDelItem"
                  @drag="handleDrag($event, item)"></dragItem>
                </el-collapse-item>
              </el-collapse>
            </div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="模板列表" name="second">
        <el-table
          :data="tableData"
          height="calc(80vh - 140px)"
          style="width: 100%">
          <el-table-column
            type="index"
            label="序号"
            align="center"
            width="50">
          </el-table-column>
          <el-table-column
            prop="name"
            label="模板名称"
            align="center"
            min-width="180">
          </el-table-column>
          <el-table-column
            prop="createdBy"
            align="center"
            label="创建者"
            width="180">
          </el-table-column>
          <el-table-column
            align="center"
            prop="createdTime"
            label="创建时间"
            width="180">
          </el-table-column>
          <el-table-column
            align="center"
            label="操作"
            width="160">
            <template slot-scope="scope">
              <el-button v-if="scope.row.isSelf" type="text" size="small" class="div-table-button--delete"
                @click="handleDeltemplate(scope.row.id)">删除</el-button>
              <el-button type="text" size="small" class="div-table-button--detail"
              @click="handlePreview(scope.row.id)">预览</el-button>
              <el-button
                         type="text"
                         size="small"
                         class="div-table-button--edit" @click="handleExportTemplate(scope.row.id)">导出</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <div v-if="activeName == 'first'" class="diy-footer">
      <div class="left">
        <div class="flex-div">
          <div>模板名称：</div>
          <el-input v-model="form.name" maxlength="20" class="wd200 mr10" />
          <div>自定义表头：</div>
          <el-input v-model="form.title" maxlength="20" class="wd200 mr10" />
          <el-checkbox v-model="form.isSaveTemp">保存为常用模板</el-checkbox>
        </div>
      </div>
      <el-button class="diy-button--delete" :loading="exportLoading" @click="handleExport">导出</el-button>
    </div>
    <el-dialog :visible.sync="diyDialog"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               width="1150px"
               append-to-body
               top="5vh"
               class="dialog-h"
               @close="handleClose"
               >
       <div style="padding: 20px;">
         <el-table
          :data="tableData"
          height="calc(80vh - 140px)"
          style="width: 100%">
          <el-table-column
            v-for="(item, index) in previewList"
            :label="item.label"
            :key="index"
            align="center"
            min-width="120">
            <el-table-column
              v-for="(n, i) in item.children"
              :label="n.label"
              :key="i"
              align="center"
              min-width="120">

            </el-table-column>
          </el-table-column>

        </el-table>
       </div>
    </el-dialog>
  </div>
</template>

<script>
import checkBox from '../../components/checkBox.vue'
import dragItem from '../../components/dragItem.vue'
import Sortable from 'sortablejs'
import { requestPost } from "@/js/dai/request"
export default {
  props: {
    list: {
      type: Array,
      default: () => []
    },
    search: {
      type: Object,
      default: () => {}
    }
  },
  components: {
    checkBox,
    dragItem
  },
  data() {
    return {
      exportLoading: false,
      activeCollapse: ['1'],
      activeName: 'first',
      leftActive: '',
      info: {},
      rightList: [],
      leftList: [],
      form: {
        isSaveTemp: false,
        name: '',
        itemList: []
      },
      tableData: [],
      previewList: [],
      diyDialog: false,
    }
  },
  async created() {
    this.list.forEach(item => {
      this.$set(this.info, item.id, [])
    })
    this.leftActive = this.list[0].id
    this.leftList = [...this.list]
    this.leftList[0].queryItemList = await this.getExportChildList(this.leftList[0].id)
    console.log('infodiy----', this.leftList)
    this.getTemplateList()
  },
  watch: {
    rightList: {
      handler(val) {
        if (val.length > 0) this.dragSort()

      },
      deep: true
    },
    // list: {
    //   handler(val) {
    //     if (val.length > 0) {
    //       this.leftList = [...val]
    //       this.leftList[0].queryItemList = this.getExportChildList(this.leftList[0].id)
    //     }
    //   },
    //   deep: true,
    //   // immediate: true
    // },
  },
  methods: {
    handleChangeBox({list, pid}) {
      console.log('ccccc----', list)
      // if (list.length == 0) return
      let obj = {}
      this.leftList.forEach(item =>{
        if (item.id == pid) obj = { ...item, queryItemList: [...list] }
      })
      const groups = this.rightList.map(item => item.id)
      if (groups.includes(pid)) {
        this.rightList.forEach((item, i) => {
          if (item.id == pid ) {
            item.queryItemList = [...list]
            if (list.length == 0) this.rightList.splice(i, 1)
          }
        })
      } else {
        this.rightList.push(obj)

        this.$nextTick(() => {
          console.log('itemttt------', this.$refs[`drag${pid}`])
          this.$refs[`drag${pid}`][0].dragSort()
        })
      }
      this.activeCollapse = [...this.activeCollapse, pid]
    },
    handleTabsClick(val) {
      console.log('tabs-----', val)
      this.leftList.forEach(async item => {
        if (item.id == val.name) {
          if (item.queryItemList.length == 0) item.queryItemList = await this.getExportChildList(item.id)
        }
      })
    },
    handleDelItem(val) {
      const { item, index } = val
      console.log('item------', item, this.$refs[`checkbox${item.itemGroupId}`])
      let checkList = this.$refs[`checkbox${item.itemGroupId}`][0].checkedList
      checkList.forEach((n, i) => {
        if (n == item.itemId) {
          checkList.splice(i, 1)
          this.$refs[`checkbox${item.itemGroupId}`][0].handleChange(checkList)
        }
      })
      this.rightList.forEach((n, i) => {
        if (n.id === item.itemGroupId) {
          n.queryItemList.splice(index, 1)
          if (n.queryItemList.length === 0) this.rightList.splice(i, 1)
        }
      })

    },
    dragSort() {
      const el = document.getElementById('collapsWr')
      this.sortTable = Sortable.create(el, {
        group: 'el-collapse-item',
        ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
        animation: 500,
        delay: 0,
        onEnd: evt => {
          console.log('evt----', evt)
          const targetRow = this.rightList.splice(evt.oldIndex, 1)[0]
          this.rightList.splice(evt.newIndex, 0, targetRow)
        }
      })
    },
    handleDrag(val, item) {
      console.log('drag-----', val)
      console.log('drag-----', item)
      this.rightList.forEach((n, i) => {
        if (item.id == n.id) n.queryItemList = [...val]
      })
    },
    handleClose() {
      this.previewList = []
      this.diyDialog = false
    },
    handleDeltemplate(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.delTemplate(id)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        })
    },
    handlePreview(id) {
      if (id) this.getPreview(id)
      else {
        if (this.rightList.length == 0) return this.$message.error('请选择导出信息')
        this.previewList = this.rightList.map(item => {
        return {
          label: item.label,
          children: item.queryItemList
        }
      })
      }
      this.diyDialog = true
    },
    handleExport() {
      if (this.rightList.length === 0) return this.$message.error('请选择导出信息')
      if (this.form.isSaveTemp && !this.form.name) return this.$message.error('请输入模板名称')
      this.exportLoading = true
      this.exportTemplate()

    },
    handleExportTemplate(id) {
      this.exportTemplate(id)
    },
    async exportTemplate(id) {
      let url = "/actual/base/residentBaseInfo/exportExcelCustom"

      let params = {
        templateId: id || '',
        searchForm: {...this.search},
        formCode: 'resident_base_info',
        exportConfig: {
          ...this.form,
          formCode: 'resident_base_info',
          itemList: this.rightList.map(item => {
            return {
              itemId: item.id,
              label: item.label,
              tableName: item.queryItemList[0].tableName,
              children: item.queryItemList,
              supportAdd: item.supportAdd
            }
          })
        }
      }
      await this.$http({
        method: 'POST',
        url,
        responseType: 'blob',
        data: params
      })
        .then(res => {
          console.log('res----dddd', res)
          // this.download(res.data, title + '.xls')
          // this.getTemplateList()

          this.exportLoading = false
          // if (res.data.code && res.data.code == 9999) {
          //   return this.$message.error(res.data.msg)
          // }
          this.formatData(res)

        })
        .catch(err => {
          console.log('err', err)
          this.exportLoading = false
          return this.$message.error('网络错误')
        })
    },
    async getTemplateList () {
      let params = {
        formCode: 'resident_base_info'
      }
      await this.$http
        .post('/oper/customize/icExportTemplate/templateList', params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            this.tableData = res.data
          }
        })
        .catch(() => {
          return this.$message.error('网络错误')
        })
    },
    async getPreview (id) {
      let params = {
        id: id || ''
      }
      await this.$http
        .post('/oper/customize/icExportTemplate/templateDetail', params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            this.previewList = res.data
          }
        })
        .catch(() => {
          return this.$message.error('网络错误')
        })
    },
    async delTemplate(id) {
      let params = [id]
      await this.$http
        .post('/oper/customize/icExportTemplate/delete', params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getTemplateList()
          }
        })
        .catch(() => {
          return this.$message.error('网络错误')
        })
    },
    async getExportChildList (groupId) {
      const url = `/oper/customize/icformitem/getItemList/${groupId}`
      let params = {}

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {

        return data

      } else {
        this.$message.error(msg)
      }
    },
    formatData(res) {
      const fileReader = new FileReader()
      fileReader.onloadend = () => {
        try {
          const jsonData = JSON.parse(fileReader.result) // 说明是普通对象数据，后台转换失败
          // 后台信息
          console.log('jsonData---1', jsonData)
          return this.$message.error(jsonData.msg)
        } catch (err) { // 解析成对象失败，说明是正常的文件流
          // 下载文件
          console.log('errr-----', err, this)
          this.downloadFile(res)
        }
      }
      fileReader.readAsText(res.data)
    },
    downloadFile(res) {
      if (res.headers["content-disposition"]) {
        let fileName = window.decodeURI(res.headers["content-disposition"].split(";")[1].split("=")[1])
        console.log('filename', fileName)
        let blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
        var url = window.URL.createObjectURL(blob)
        var aLink = document.createElement('a')
        aLink.style.display = 'none'
        aLink.href = url
        aLink.setAttribute('download', fileName)
        document.body.appendChild(aLink)
        aLink.click()
        document.body.removeChild(aLink) //下载完成移除元素
        window.URL.revokeObjectURL(url) //释放掉blob对象
        this.$message.success('导出成功')
        this.$emit('close')
      } else this.$message.error('下载失败')
    }
  }
}
</script>

<style lang="scss" scoped>
.diy-container {
  padding: 20px 20px 0 20px;
}
.diy-wr {
  display: flex;
  width: 100%;
  height: calc(80vh - 120px);
  .left {
    width: 49%;
    height: 100%;
    .check-boxwr  {
      height: calc(80vh - 120px);
      overflow: auto;
    }
  }
  .right {
    flex-shrink: 0;
    width: 50%;
    height: 100%;
    box-sizing: border-box;
    margin-left: 20px;
    padding: 0 20px;
    border-left: 1px solid #eee;
    .right-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding-bottom: 10px;
      // border-bottom: 1px solid #eee;
      .title {
        font-weight: 500;
      }
    }
  }
}
.h80 {
  height: calc(80vh - 160px);
  overflow: auto;
}
.diy-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 10px;
}
.left-h {
  height: 100%;
  ::v-deep .el-tabs__header.is-left,
  ::v-deep .el-tabs__nav-wrap.is-left::after {
    height: calc(80vh - 120px);
  }
}
.flex-div {
  display: flex;
  align-items: center;
}
// #collapsWr {
//   .col-h {
//     ::v-deep .el-collapse-item__wrap {
//       max-height: calc(80vh - 220px);
//       // overflow: auto;
//     }

//   }
// }
.mb10 {
  margin-bottom: 10px;
}
.pd10 {
  padding: 10px;
}
.mr10 {
  margin-right: 10px;
}
.wd200 {
  width: 200px;
}
</style>
