<template>
  <div style="margin-bottom:10px">
    <div style="display:flex;justify-content:flex-end" v-if="!readonly">
      <el-button size="mini" @click="onDownloadTemplate">下载方案模板</el-button>
      <el-button size="mini" type="primary" @click="handleUploadVisible">上传活动方案</el-button>
    </div>

    <ex-table
      :columns="[
        { type:'selection'},
        ...columns
      ]"
      @selection-change="handleSelection"
      :table="table"
      :data="planList"
      style="margin: 15px 0 0 0"
      noPagination
    >
      <template #is_check="{scope}">
        <el-tag size="mini" :type="String(scope.row.is_check) === '2' ? '' :'info'">
         {{String(scope.row.is_check) === "2" ?  "已选择" : "未选择"}}
        </el-tag>
      </template>

    </ex-table>
    <letter-modal :visible.sync="xlsxVisible" :id="currentId" :sitem="sitem" :title="title" @refresh="refresh" />
  </div>
</template>

<script>
import { columns } from "./_columns"
import { template } from "./_template"
import LetterModal from "./letterEditing.vue"
import { writeFile, utils } from "xlsx";
import { budgetStatusOptions } from '@/assets/js/statusList';
import asyncRequest from "@/apis/service/customerService/workbench";

export default {
  name:'SettlementBudgetLetter',
  props:["sitem","readonly", "evalute", "id"],
  components:{ LetterModal },
  data(){
    return {
      currentId: 0,
      budgetStatusOptions,
      title: '评估预算函',
      table: {
        stripe: true,
        border: true,
        'max-height': '800px'
      },
      loading:true,
      template,
      columns,
      planList:[],
      xlsxVisible:false
    }
  },
  watch:{
    'sitem':{
      handler(val = {}){
        const { id } = val
        if(!id) return
        this.searchList(id)
      },
      immediate: true,
      deep:true
    }
  },
  methods:{
    refresh(){
      this.$emit('refresh')
    },
    handleSelection(val){
      this.$emit('selectionChange', val.map(({id}) => id))
    },
     async searchList(id){
      this.loading = true
      const { code, data }  = await asyncRequest.planList({ req_id: id ? id :this.sitem.id ,status:2})
      this.loading = false

      if(code === 1){
        const { list = [], count = 0 } = data
        this.planList = list;
        this.pageInfo.total = count
      }
    },
    handleUploadVisible(){
      if(this.evalute.length === 0){
        this.$message.warning('必须选择一个评估预算函')
        return
      }

      if(this.evalute.length > 1){
        this.$message.warning('只能选择一个评估预算函')
        return
      }

      this.currentId = this.evalute[0]
      this.xlsxVisible = true
    },
    onDownloadTemplate(){
      const workBook = utils.book_new()
      const workSheet = utils.json_to_sheet(template)
      utils.book_append_sheet(workBook,workSheet,"sheet")
      writeFile(workBook,`${this.title}模板.xlsx`,{
        bookType:'xlsx'
      })
    }
  }
}
</script>
