<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="xlsxVisible = true">上传评估预算函</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) === '1' ? '' :'info'">
         {{String(scope.row.is_check) === "1" ?  "已选择" : "未选择"}}
        </el-tag>
      </template>
    </ex-table>

    <letter-modal 
      :visible.sync="xlsxVisible" 
      :sitem="sitem" 
      :title="title" 
      :storeId="storeId" 
      @refresh="refresh" 
    />
  </div>
</template>

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

export default {
  name:'SettlementBudgetLetter',
  props:["sitem", "readonly", "storeId"],
  components:{ LetterModal },
  data(){
    return {
      budgetStatusOptions,
      title: '评估预算函',
      table: {
        stripe: true,
        border: true,
        'max-height': '800px'
      },
      pageInfo:{},
      planList:[],
      template,
      columns,
      tableData:[],
      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: 1 })
      this.loading = false

      if(code === 1){
        const { list = [], count = 0 } = data
        this.planList = list;
        this.pageInfo.total = count
      }
    },
    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>
