<template>
  <div>
    <div style="display:flex;justify-content:flex-end" v-if="!readonly">
      <el-button size="mini" @click="onUpdateLetter(false)" v-if="type === 'project'">编辑预算函</el-button>
      <el-button size="mini" @click="onDownloadTemplate" v-if="type !== 'activity'">下载{{mapTitle[type]}}模板</el-button>
      <el-button size="mini" type="primary" @click="handleUploadModalVisible">上传{{mapTitle[type]}}</el-button>
    </div>

    <ex-table
      :columns="[
        ...(isSelection ? [{ type: 'selection' }] : []),
        ...mapColumns[type || 'budget'], { label: '操作', _slot_: 'action', width: '100px',fixed:'right'}
      ]"
      @page-curr-change="handlePageChange"
      @page-size-change="handleSizeChange"
      :page="pageInfo"
      @screen-reset="
        pageInfo.curr = 1;
        parmValue.page = 1;
        searchList();
      "
      @screen-submit="
        pageInfo.curr = 1;
        parmValue.page = 1;
        searchList();
        "
      @selection="handleSelection"
      :table="table"
      :data="tableData"
      style="margin: 15px 0 0 0"
    >

      <template #letter="{scope}">
        <a v-if="scope.row.plan_file" :href="scope.row.plan_file">{{getFileNameWithUrl(scope.row.plan_file)}}</a>
        <p v-else>--</p>
      </template>
      
      <template #is_check="{scope}">
        <el-tag size="mini" :type="Number(scope.row.is_check) === mapCheck[type || 'budget'].ok ? '' :'info'">
         {{ Number(scope.row.is_check) === mapCheck[type || 'budget'].ok  ?  "已选择" : "未选择" }}
        </el-tag>
      </template>

      <template #action="{ scope }">
        <!-- type === 'budget' && -->
        <el-button 
          v-if="(Number(scope.row.is_check) !== mapCheck[type].ok)" type="text" 
          size="mini" 
          @click="linkToLetterUpdate(scope.row)"
        >编辑</el-button>
        <el-button 
          v-if="type === 'budget' && Number(scope.row.is_check) !== mapCheck[type].ok" 
          type="text" 
          size="mini" 
          @click="deleteItem(scope.row)"
        >删除</el-button>
      </template>
    </ex-table>

    <excel-upload-modal 
      :requsetMethod="requsetMethod"
      :visible.sync="xlsxVisible"
      @submit="handleSubmit"
      @refresh="refresh"
      @activitySubmit="file => onUpdateLetter(file)"
      :isFile="isFile"
      :title="title" 
      :type="type"
    />

    <preview-modal 
      :sitem="sitem"
      :visible.sync="previewVisible"
    />
  </div>
</template>


<script>
import { mapColumns, mapCheck, mapTitle } from "./_columns"
import ExcelUploadModal from "./xlsxUploadModal.vue"
import asyncRequest from "@/apis/components/letter"
import PreviewModal from "./previewModal.vue"
import { writeFile, utils } from "xlsx";
import { template ,mapLetterToType } from "./_template"
import mixinPage from "@/mixins/elPaginationHandle";

export default {
  name:'Letter',
  mixins:[mixinPage],
  /* type:budget预算函  activity活动方案  project计划 **/
  props:['title', 'requsetMethod', 'status', 'id', 'isSelection', 'readonly','type', 'beforeModalVisible', 'isFile', 'updateLoading'],
  components:{ ExcelUploadModal, PreviewModal },
  data(){
    return {
      table: {
        stripe: true,
        border: true,
        'max-height': '800px'
      },
      parmValue:{
        page: 1, // 页码
        size: 15, // 每页显示条数
      },
      pageInfo: {
        size: 15,
        curr: 1,
        total: 0,
      },
      sitem: {},
      mapCheck,
      mapTitle,
      mapColumns,
      tableData:[],
      xlsxVisible:false,
      previewVisible:false
    }
  },
  watch:{
    id:{
      handler(val){
        if(!val) return
        this.searchList()
      },
      immediate:true
    }
  },
  methods:{
    async onUpdateLetter(fileUrl){
      if(this.beforeModalVisible && !this.beforeModalVisible()){
        return
      }

      this.updateLoading(true)
      const { form, id } = this.beforeModalVisible()
      const { code, data } = await asyncRequest.detail({id})
      
      if(code !== 1) {
        this.updateLoading(false)
        return
      }

      const { planinfo = [], req_id, store_id, plan_file } = data;

      const plan_info =  planinfo.map(
        ({ name,service_cat,unit,price,num,remark,total_fee,tax,pay_fee,tax_fee  }) =>
        ({ name,service_cat,unit,price,num,remark,total_fee,tax,pay_fee,tax_fee  })
      )

      console.log(plan_info)

      const letter = await asyncRequest.create({
        plan_type: mapLetterToType[form],
        file: fileUrl ? fileUrl : plan_file,
        plan_info,
        store_id,
        req_id
      })

      this.updateLoading(false)

      if(fileUrl){
        this.searchList()
        return
      }

      if(letter.code !== 1) return
      //创建获取获取新id进入编辑页...
      this.$router.push(`/customerService/letterEditing?id=${letter.data.id}&from=${form}&type=create`)
    },
    refresh(){
      this.searchList()
      this.$emit('refresh')
    },
    handleSelection({list}){
      this.$emit('selection', list.map(({id}) => id))
    },
    deleteItem(row){
      this.$confirm(`确认删除评估预算函 ${row.planCode}?`,{
        type:'warning'
      }).then(async () => {
        this.loading = true
        const { code } = await asyncRequest.delete({id:row.id})
        this.loading = false
        if(code !== 1) return
        this.searchList()
      })
    },
    openModal(row){
      this.sitem = row
      this.previewVisible = true
    },
    onDownloadTemplate(){
      const workBook = utils.book_new()
      const workSheet = utils.json_to_sheet(template)
      utils.book_append_sheet(workBook,workSheet,"sheet")
      writeFile(workBook,`${mapTitle[this.type]}模板.xlsx`,{
        bookType:'xlsx'
      })
    },
    linkToLetterUpdate(row){
      this.$router.push('/customerService/letterEditing?id=' + row.id)
    },
    getFileNameWithUrl(url){
      const chunks = url.split('/')
      const fullFileName = chunks[chunks.length - 1]
      const [ fileName, suffix ] = fullFileName.split('.')
      return (fileName.length > 10 ? fileName[0] + fileName[1]  + '...' + fileName[fileName.length -1] : fileName) + '.' + suffix
    },
    handleUploadModalVisible(){
      if(this.type !== 'project' && (this.beforeModalVisible && !this.beforeModalVisible())){
        return
      }
      this.xlsxVisible = true
    },

    async searchList(){
      // if(this.type === 'settlement') return
      this.loading = true
      const { code, data } = await asyncRequest.list({ 
          plan_type :this.status,          
          req_id: this.id ,
          ...this.parmValue
        })
      this.loading = false
      if(code !== 1) return
      this.tableData = data.list
      this.pageInfo.total = Number(data.count)
    }
  }
}
</script>

<style lang="scss" scoped>
a{
  color: #409EFF !important;
}
</style>
