<template>
  <div class="sandList-container">
    <div class="main-top">
      <el-button type="primary" @click="addSand">添加沙盘</el-button>
      <div>
        <el-input
          v-model="search_txt"
          style="width: 250px; margin-right: 20px"
          placeholder="沙盘名称"
        >
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
        <el-cascader
          :options="classifyArr"
          :props="classifyProps"
          v-model="classify"
          clearable
          placeholder="品种筛选"
        />
      </div>
    </div>
    <div class="main-bottom">
      <el-table
        :data="tableData"
        style="box-shadow: 0px 3px 6px rgba(155, 170, 219, 0.2)"
        :key="tableKey"
        row-key="VersionCode"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :load="loadChildList"
        @sort-change="sortChangeHandle"
        element-loading-text="加载中..."
        v-loading="tableLoading"
        lazy
        border
        max-height="600"
        ref="table"
      >
        <el-table-column
          v-for="item in tableColums"
          :key="item.label"
          :label="item.label"
          :prop="item.key"
          :width="item.widthsty"
          :min-width="item.minwidthsty"
          :sortable="item.sortable"
          align="center"
        >
        <!-- :sortable="item.sortable?'custom':false" -->
          <template slot-scope="scope">
            <span>{{ scope.row[item.key] }}</span>

            <el-button
              size="mini"
              type="text"
              v-if="scope.row.key === 'more' && item.key === 'CurrVersion'"
              @click.native="openHistorySand(scope.row)"
              >更多</el-button
            >
          </template>
        </el-table-column>
        <el-table-column width="260" align="center" label="操作">
          <template slot-scope="scope">
            <template v-if="scope.row.key !== 'more'">
              <el-button
                size="mini"
                type="text"
                @click="handleSand(scope.row, 'edit')"
                v-if="scope.row.CanEdit"
                >编辑</el-button
              >
              <el-button
                size="mini"
                type="text"
                @click="handleSand(scope.row, 'edit')"
                v-if="!scope.row.CanEdit"
                >{{scope.row.Editor||''}}编辑中...</el-button
              >
              <el-button
                size="mini"
                type="text"
                style="color: #f00"
                @click="handleSand(scope.row, 'del')"
                >删除</el-button
              >
              <el-button
                size="mini"
                type="text"
                @click="handleSand(scope.row, 'view')"
                >查看</el-button
              >
              <el-button size="mini" type="text" @click="copyImg(scope.row)"
                >复制图片</el-button
              >
            </template>
          </template>
        </el-table-column>

        <div slot="empty" style="padding: 50px 0 50px">
          <img
            src="~@/assets/img/data_m/table_no.png"
            alt=""
            style="
              display: block;
              width: 135px;
              height: 90px;
              margin: 20px auto 10px;
            "
          />
          <span>暂无数据</span>
        </div>
      </el-table>
    </div>

    <!-- 历史版本弹窗 -->
    <m-dialog
      :show.sync="openHistoryDia"
      width="700px"
      title="历史版本"
      @close="closeDialog"
    >
      <div class="history-version-wrapper">
        <el-table
          :data="historyList"
          style="box-shadow: 0px 3px 6px rgba(155, 170, 219, 0.2)"
          border
        >
          <el-table-column
            v-for="item in hitoryColums"
            :key="item.label"
            :label="item.label"
            :width="item.widthsty"
            :min-width="item.minwidthsty"
            align="center"
          >
            <template slot-scope="scope">
              <span>{{ scope.row[item.key] }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="editChildSand(scope.row)" v-if="scope.row.CanEdit">编辑</el-button>
              <!-- <el-button size="mini" type="text" @click="handleSand(scope.row, 'editing')" v-else>{{scope.row.Editor||''}}编辑中...</el-button> -->
              <el-button size="mini" type="text" @click="editChildSand(scope.row)" v-else>{{scope.row.Editor||''}}编辑中...</el-button>
              <el-button size="mini" type="text" style="color: #f00" @click="removeChildSand(scope.row)">删除</el-button>
              <el-button size="mini" type="text" @click="handleSand(scope.row, 'view')">查看</el-button>
              <el-button size="mini" type="text" @click="copyImg(scope.row)">复制图片</el-button>
            </template>
          </el-table-column>

          <div slot="empty" style="padding: 50px 0 50px">
            <img
              src="~@/assets/img/data_m/table_no.png"
              alt=""
              style="
                display: block;
                width: 135px;
                height: 90px;
                margin: 20px auto 10px;
              "
            />
            <span>暂无数据</span>
          </div>
        </el-table>
        <el-row style="margin-top: 30px">
          <m-page
            :page_no="history_page"
            :pageSize="history_pageSize"
            :total="history_total"
            @handleCurrentChange="hitoryPageChange"
          />
        </el-row>
      </div>
    </m-dialog>
  </div>
</template>

<script>
import { sandInterface, customInterence } from '@/api/api.js';
import mPage from '@/components/mPage';
import mDialog from '@/components/mDialog';
import { copyBlob } from '@/utils/svgToblob'
export default {
  name: '',
  components: { mPage, mDialog },
  data() {
    return {
      search_txt: '',
      classify: [],
      classifyProps: {
        children: 'Items',
        label: 'ClassifyName',
        value: 'ChartPermissionId',
      },
      classifyArr: [],
      tableLoading: false,
      lockLoding:null,
      tableData: [],
      tableColums: [
        {
          label: '沙盘名称',
          key: 'Name',
          minwidthsty: '100px',
        },
        {
          label: '品种',
          key: 'ChartPermissionName',
        },
        {
          label: '版本',
          key: 'CurrVersion',
          widthsty: '100px',
        },
        {
          label: '更新时间',
          key: 'ModifyTime',
          minwidthsty: '120px',
          /* sortable:true */
        },
        {
          label: '更新人',
          key: 'OpUserName',
          widthsty: '120px',
        },
      ],
      page_no: 1,
      pageSize: 100,
      total: 0,
      openHistoryDia: false, //历史沙盘弹窗
      historyList: [],
      hitoryColums: [
        {
          label: '版本',
          key: 'CurrVersion',
          widthsty: '100px',
        },
        {
          label: '更新时间',
          key: 'ModifyTime',
          minwidthsty: '100px',
        },
        {
          label: '更新人',
          key: 'OpUserName',
          widthsty: '100px',
        },
      ], //历史表格数据列

      open_sandid: '', //打开的沙盘id
      history_page: 1,
      history_pageSize: 10,
      history_total: 0,
      tableBody:null,//表单body的dom,用于监听滚动事件 

      tableKey: 0,//数据更新了 表格不更新的问题
    };
  },
  watch: {
    search_txt() {
      this.page_no = 1;
      this.getTableData();
    },
    classify() {
      this.page_no = 1;
      this.getTableData();
    },
  },
  methods: {
    /* 获取表格数据 */
    getTableData: _.debounce(function () {
      this.tableLoading = true;

      sandInterface
        .sandlist({
          PageSize: this.pageSize,
          CurrentIndex: this.page_no,
          Keyword: this.search_txt,
          ChartPermissionId: this.classify.length ? this.classify[1] : 0,
        })
        .then((res) => {
          if (res.Ret !== 200) return;
          const {Data} = res
          const {List,Paging} = Data
          const resData = List.length?res.Data.List.map((item) => ({
                hasChildren: item.VersionTotal > 1,
                ...item,
                ModifyTime: this.$moment(item.ModifyTime).format(
                  'YYYY-MM-DD HH:mm:ss'
                ),
              }))
            : [];

					this.tableData = this.page_no===1 ? resData :  this.tableData.concat(resData);	
          this.total = Paging.Totals;
          this.tableLoading = false;
          this.isLastPage = Paging.IsEnd
          this.tableKey ++;
        });
    }, 300),

    loadChildList(node, prop, resolve) {
      const { SandboxId,CanEdit } = node;
      sandInterface.childList({ SandboxId }).then((res) => {
        if (res.Ret !== 200) return;

        let arr = res.Data.List.length
          ? res.Data.List.map((item) => ({
              ...item,
              hide_name : item.Name,
              Name: '',
              ChartPermissionName: '',
              isChildList: true,
              ModifyTime: this.$moment(item.ModifyTime).format(
                'YYYY-MM-DD HH:mm:ss'
              ),
              CanEdit
            }))
          : [];

        res.Data.Paging.Totals > 3
          ? resolve([
              ...arr,
              {
                key: 'more',
                VersionCode: new Date().getTime(),
                SandboxId: res.Data.List[0].SandboxId,
              },
            ])
          : resolve(arr);
      });
    },

    /* 获取品种 */
    getClassify() {
      customInterence
        .getvariety({
          CompanyType: 'ficc',
        })
        .then((res) => {
          if (res.Ret !== 200) return;
          this.classifyArr = res.Data.List;
        });
    },

    /* 添加沙盘 */
    addSand() {
      const { href } = this.$router.resolve({ path: '/sandflow' });
      window.open(href, '_blank');
    },

    goDetail(SandboxId, VersionCode, type) {
      const { href } = this.$router.resolve({
        path: '/sandflow',
        query: {
          id: VersionCode,
          type,
        },
      });
      window.open(href, '_blank');
    },

    /* 编辑 删除沙盘 */
    handleSand(item, type) {
      const { SandboxId, VersionCode } = item;
      if (type === 'edit') {
        // 编辑前校验
        sandInterface
          .mark({
            SandboxId,
            Status: 1,
          })
          .then((res) => {
            // if (res.Ret !== 200) return;
            if(res.Ret===200){
              if(res.Data.Status==1){
                this.$message.warning(res.Data.Msg || '沙盘图正在编辑，不可重复编辑')
                item.CanEdit=false;
                item.Editor=res.Data.Editor || ''
                return
              }else if(res.Data.Status==0){
                if(!item.CanEdit){
                  this.getTableData();
                }
                // item.CanEdit=true;
                // item.Editor=res.Data.Editor || ''
              }
            }else{
              this.$message.error(res.ErrMsg || '未知错误，请稍后重试')
              return
            }
            this.goDetail(SandboxId, VersionCode, type);
          });
      }

      type === 'view' && this.goDetail(SandboxId, VersionCode, type);

      // type === 'editing' && this.$message.warning('沙盘图正在编辑，不可重复编辑');

      type === 'del' && this.delHandle(item)
        
    },

    /* 弹窗内的删除 */
    removeChildSand({VersionCode,Name,CurrVersion}) {
      this.$confirm(`<p>确定删除【<span style="color:#409EFF">${Name}</span>】沙盘图<span style="color:#409EFF">版本${CurrVersion}</span>？<p>`, '提示', {
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        sandInterface.sandDelVersion({ SandboxVersionCode:VersionCode }).then((res) => {
          if (res.Ret !== 200) return;
          this.$message.success('删除成功');
          this.historyList.splice(this.historyList.findIndex(_ => _.VersionCode === VersionCode),1)
          this.page_no = 1;
          this.getTableData();
        });
      }).catch(()=>{})
    },

    editChildSand(item) {
      ({SandboxId,VersionCode,type} = item)
       // 编辑前校验
      sandInterface
        .mark({
          SandboxId,
          Status: 1,
        })
        .then((res) => {
          // if (res.Ret !== 200) return;
          if(res.Ret===200){
            if(res.Data.Status==1){
              this.$message.warning(res.Data.Msg || '沙盘图正在编辑，不可重复编辑')
              item.CanEdit=false;
              item.Editor=res.Data.Editor || ''
              return
            }else if(res.Data.Status==0){
              if(!item.CanEdit){
                this.getTableData();
              }
              // item.CanEdit=true;
              // item.Editor=res.Data.Editor || ''
            }
          }else{
            this.$message.error(res.ErrMsg || '未知错误，请稍后重试')
            return
          }
          this.goDetail(SandboxId, VersionCode, type);
        });
    },

    /* 删除图 */
    delHandle(item) {
      const { SandboxId, VersionCode,isChildList,CurrVersion,hide_name } = item;
      isChildList 
        ? this.$confirm(`<p>确定删除【<span style="color:#409EFF">${hide_name}</span>】沙盘图<span style="color:#409EFF">版本${CurrVersion}</span>？<p>`, '提示', {
            type: 'warning',
            dangerouslyUseHTMLString: true
          }).then(() => {
            sandInterface.sandDelVersion({ SandboxVersionCode:VersionCode }).then((res) => {
              if (res.Ret !== 200) return;
              this.$message.success('删除成功');
              this.page_no = 1;
              this.getTableData();
            });
          }).catch(()=>{})
        : this.$confirm('确定删除该沙盘图（包括所有历史版本）？', '提示', {
            type: 'warning',
          }).then(() => {
            sandInterface.sanDelete({ SandboxId }).then((res) => {
              if (res.Ret !== 200) return;
              this.$message.success('删除成功');
              this.page_no = 1;
              this.getTableData();
            });
          }).catch(()=>{});


    },

    /* 历史沙盘版本表格 */
    getHistoryTable(SandboxId) {
      sandInterface
        .verisonlist({
          PageSize: this.history_pageSize,
          CurrentIndex: this.history_page,
          SandboxId,
        })
        .then((res) => {
          if (res.Ret !== 200) return;

          this.historyList =
            res.Data.List &&
              res.Data.List.map((item) => ({
                ...item,
                ModifyTime: this.$moment(item.ModifyTime).format(
                  'YYYY-MM-DD HH:mm:ss'
                ),
              })) ||
            [];

          this.history_total = res.Data.Paging.Totals;
        });
    },

    /* 查看历史沙盘 */
    openHistorySand({ SandboxId }) {
      this.open_sandid = SandboxId;
      this.getHistoryTable(SandboxId);
      this.openHistoryDia = true;
    },

    /* 关闭弹窗 */
    closeDialog() {
      this.openHistoryDia = false;
      this.history_page = 1;
    },

    /* 复制图片 */
    copyImg: _.debounce(function ({ PicUrl }) {

      /* const copyImg = document.createElement('img');
      $('.sandList-container')[0].appendChild(copyImg);
      copyImg.src = PicUrl;

      this.getSelect(copyImg);
      setTimeout(() => {
        document.execCommand('copy');
        $('.sandList-container')[0].removeChild(copyImg);
        this.$message.success('复制成功');
      }); */
      this.lockLoding = this.$loading({
        lock: true,
        text: '复制图片中...',
        target: '.main-bottom',
        spinner: 'el-icon-loading',
        background: 'rgba(255, 255, 255, 0.8)'
      });
      const canvas = document.createElement("canvas");
      const ctx = canvas.getContext("2d");
      const img = new Image();
      img.crossOrigin = "Anonymous";
      img.src = PicUrl;
      img.onload = ()=>{
        canvas.width = img.width;
        canvas.height = img.height;
        ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
        ctx.fillStyle="#fff";
        ctx.fillRect(0, 0, img.width, img.height);
        ctx.drawImage(img, 0, 0);
        canvas.toBlob(async (blob) => {
          const data = [new ClipboardItem({ [blob.type]: blob })]; 
          await navigator.clipboard.write(data).then(
            () => {
             this.$message.success('复制成功！')
            },
            () => {
              this.$message.success('复制失败,稍后再试')
            }
          ).finally(()=>{
                        this.lockLoding && this.lockLoding.close();
                    });
        });
      }
    }, 500),
    /* 排序 */
    sortChangeHandle(sortInfo){
      const sortColumn = ['更新时间']
      const {column,order} = sortInfo
      if(!sortColumn.includes(column.label)) return
      //重新请求排序
      console.log(sortInfo)
    },
    /* 滚动条事件 */
    handleScroll:_.throttle(function(){
      const {scrollTop,clientHeight,scrollHeight} = this.tableBody
      if(scrollTop + clientHeight >= scrollHeight-10 && !this.isLastPage&&this.total!==this.tableData.length){
				this.page_no++;
				this.getTableData();
			}
    },300),
    // 选择
    getSelect(targetNode) {
      if (window.getSelection) {
        //chrome等主流浏览器
        var selection = window.getSelection();
        var range = document.createRange();
        range.selectNode(targetNode);
        selection.removeAllRanges();
        selection.addRange(range);
      } else if (document.body.createTextRange) {
        //ie
        var range = document.body.createTextRange();
        range.moveToElementText(targetNode);
        range.select();
      }
    },
    /* 页码改变 */
    handleCurrentChange(page) {
      this.page_no = page;
      this.getTableData();
    },

    hitoryPageChange(page) {
      this.history_page = page;
      this.getHistoryTable(this.open_sandid);
    },
  },
  mounted() {
    this.getTableData();
    this.getClassify();
    this.tableBody = this.$refs.table.bodyWrapper
    this.tableBody.addEventListener('scroll',this.handleScroll)
  },
  beforeDestroy(){
    this.tableBody.removeEventListener('scroll',this.handleScroll)
  }
};
</script>
<style lang="scss">
.sandList-container {
  .main-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 28px;
    padding: 20px 30px;
    background: #fff;
    border: 1px solid #ececec;
    border-radius: 4px;
    box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
  }
  .main-bottom {
    padding: 20px 30px;
    background: #fff;
    border: 1px solid #ececec;
    border-radius: 4px;
    box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.05);
    .el-table {
      height:600px;
      .el-table__row--level-1 {
        td {
          border-right: none;
        }
      }
      .el-table__expand-icon {
        position: absolute;
        left: 5px;
        .el-icon-arrow-right {
          font-size: 14px;
        }
      }
      
      th.gutter{
        background-color:#F0F2F5 !important;
      }
      ::-webkit-scrollbar{
        background-color: transparent;
        &-track{
          background-color:#f5f5f5;
        }
      }
    }
  }

  .history-version-wrapper {
    padding: 0 20px;
  }
}
</style>
