<template>
  <div class="edit-BI-board-page">
    <div class="top-box">
      <el-input
        placeholder="请输入看板名称"
        v-model="name"
        style="width: 300px; margin-right: 20px"
      ></el-input>
      <el-button type="primary" plain @click="showSelectTable = true"
        >添加表格</el-button
      >
      <el-button type="primary" plain @click="showSelectChart = true"
        >添加图表</el-button
      >
      <el-dropdown @command="handleCommand">
        <el-button type="primary" style="margin-left: 10px;">
          添加知识资源<i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="0">事件库</el-dropdown-item>
          <el-dropdown-item command="1">政策库</el-dropdown-item>
          <el-dropdown-item command="2">报告库</el-dropdown-item>
          <el-dropdown-item command="3">知识库</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <div class="right-btns">
        <el-button type="primary" plain @click="$router.back()">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </div>
    </div>
    <!-- 看板内容模块 -->
    <BIBoardContent 
      ref="boardContent" 
      :knowList.sync="knowledgeList" 
      renderHeight="calc(100vh - 190px)"
      @checkDataList="checkDataList"
      v-model="boardDataList" 
      :canDelete="true" 
      :canDrag="true" />

    <!-- 选择图表 -->
    <SelectChart
      v-model="showSelectChart"
      @addChart="handleAddComp('chart', $event)"
    />
    <!-- 选择表格 -->
    <SelectTable
      v-model="showSelectTable"
      @addTable="handleAddComp('table', $event)"
    />
    <!-- 选择知识资源 -->
    <SelectKnow
      :show.sync="showSelectKnow"
      :ResourceType="selectKnowType"
      :knowList="knowledgeList"
      @addKnow="handleAddKnow"
    />
  </div>
</template>

<script>
import apiBiBoard from '@/api/modules/BIBoard.js'
import BIBoardContent from './components/BoardContent.vue'
import SelectChart from './components/SelectChart.vue'
import SelectTable from './components/SelectTable.vue'
import SelectKnow from './components/SelectKnow.vue'
const MAX_COUNT = 50
// 生成唯一ID 
function createUniqueIdGenerator() {
  let id = 0;
  return function generateUniqueId() {
    id += 1;
    return `selfId_${id}`;
  };
}
const getUniqueId = createUniqueIdGenerator();

export default {
  components: {
    BIBoardContent,
    SelectChart,
    SelectTable,
    SelectKnow,
  },
  data() {
    return {
      name: '',
      boardDataList: [],
      knowledgeList:[],//知识资源模块列表的全部数据

      showSelectChart: false,
      showSelectTable: false,
      showSelectKnow: false,
      selectKnowType:0,
    }
  },
  created() {
    if(this.$route.query.id){
      this.getBoardDetail()
    }
  },
  methods: {
    handleCommand(command){
       this.selectKnowType = +command || 0;
       this.showSelectKnow = true;
    },
    // 获取看板详情
    async getBoardDetail(){
      const res=await apiBiBoard.boardDetail({DashboardId:Number(this.$route.query.id)})
      if(res.Ret===200){
        this.name=res.Data.BiDashboardName
        this.boardDataList=res.Data.List||[]
        this.handleKnowList();
      }
    },

    async handleKnowList(){
      let item = this.boardDataList.find(_=>_.Type == 3);
      if(!item) return;
      let res = await apiBiBoard.getKnowledge({ BiDashboardDetailId:item.BiDashboardDetailId });
      if(res.Ret != 200) return;
      this.knowledgeList = res.Data.KnowledgeResourceList || [];
      this.cacheSaveKnowList(); //首次请求暂存，否则后端获取不到
      if(this.knowledgeList.length > 0) this.setFirstKnow();
    },

    async cacheSaveKnowList(){
      let knowItem = this.boardDataList.find(_=>_.Type == 3);
      await apiBiBoard.saveKnowledge({
        BiDashboardDetailId:knowItem ? (/^selfId_\d+$/.test(knowItem.BiDashboardDetailId) ? 0 : knowItem.BiDashboardDetailId) : 0,
        KnowledgeResourceList:this.knowledgeList.map(_=>({
          ResourceType:_.ResourceType,
          KnowledgeResourceId:_.KnowledgeResourceId
        }))
      });
    },

    setFirstKnow(){
      this.$nextTick(()=>{
        this.$refs.boardContent && this.$refs.boardContent.setFirstKnow()
      })
    },

    async handleSave() {
      if (!this.name) {
        this.$message.warning('请填写看板名称')
        return
      }
      if (this.boardDataList.length === 0) {
        this.$message.warning('请至少选择一个图表或表格！')
        return
      }
      const arr=this.boardDataList.map(item=>{
        return {
          Type:item.Type,
          UniqueCode:item.UniqueCode,
          Conf:item.Conf,
        }
      })
      const params={
        BiDashboardName:this.name,
        List:arr||[]
      }
      const res=this.$route.query.id?await apiBiBoard.editBoard({
        BiDashboardId:Number(this.$route.query.id),
        ...params
      }) :await apiBiBoard.addBoard(params)
      if(res.Ret===200){
        this.$message.success(this.$route.query.id?'编辑成功':'新增成功')
        setTimeout(() => {
          this.$router.back()
        }, 1000);
      }

    },
    checkDataList(dataList){ //grid-layout对x.y进行处理之后数据发生变化  同步x.y数据
      if(!dataList || !dataList.length) return;
       dataList.map((item) => { 
         let i = this.boardDataList.findIndex(_=>item.BiDashboardDetailId == _.BiDashboardDetailId && item.Type == _.Type);
         if(i >= 0 && (item.x != this.boardDataList[i].x || item.y != this.boardDataList[i].y)){
          this.boardDataList[i].x = item.x;
          this.boardDataList[i].y = item.y;
          let configs = {
            w : item.w,
            h : item.h,
            x : item.x,
            y : item.y,
            i : item.i,
          };
          this.boardDataList[i].Conf = JSON.stringify(configs);
         }
       });
    },
    async handleAddKnow(data){
      const { ResourceType, checkedList} = data;
      let knowList = [...this.knowledgeList.filter(_=>_.ResourceType != ResourceType),...checkedList];
      
      let knowItem = this.boardDataList.find(_=>_.Type == 3);
      //后端需要暂存数据
      let r = await apiBiBoard.saveKnowledge({
        BiDashboardDetailId:knowItem ? (/^selfId_\d+$/.test(knowItem.BiDashboardDetailId) ? 0 : knowItem.BiDashboardDetailId) : 0,
        KnowledgeResourceList:knowList.map(_=>({
          ResourceType:_.ResourceType,
          KnowledgeResourceId:_.KnowledgeResourceId
        }))
      });
      if(r.Ret != 200) return this.$message.warning('添加失败，请重试')
      this.knowledgeList = knowList;

      if(!knowItem){
        let i = {
          Type: 3,
          UniqueCode:'uniqueTimeCode' + new Date().getTime(),
          BiDashboardDetailId:getUniqueId()
        }
        let addItem = this.$refs.boardContent ? this.$refs.boardContent.getAddMessage([i]) : []; //处理添加内容的位置信息
        this.boardDataList = [...this.boardDataList,...addItem];
      }else {
        if(!knowList.length){
           this.boardDataList = this.boardDataList.filter(_=>_.Type != 3);
        }
      }
      this.setFirstKnow();
      this.showSelectKnow = false;
    },
    handleAddComp(type, data) {
      const arr = data || []
      if (this.boardDataList.length + arr.length > MAX_COUNT) {
        this.$message.warning('添加已达上限（上限50）！')
        return
      }
      let objs = arr.map(item => {
        return {
          Type: type == 'chart' ? 1 : 2,
          UniqueCode:item.UniqueCode,
          BiDashboardDetailId:getUniqueId()
        }
      });

      let addItems = this.$refs.boardContent ? this.$refs.boardContent.getAddMessage(objs) : []; //处理添加内容的位置信息
      this.boardDataList = [...this.boardDataList,...addItems];

      this.showSelectChart = false
      this.showSelectTable = false
    },
  },
}
</script>

<style lang="scss" scoped>
.edit-BI-board-page {
  $border-color: #c8cdd9;
  background-color: #fff;
  border: 1px solid $border-color;
  .top-box {
    padding: 14px 20px;
    border-bottom: 1px solid $border-color;
    .right-btns {
      float: right;
    }
  }
}
</style>