<template>
  <div>
    <div style="display:flex;justify-content:flex-end" v-if="!readonly">
      <el-button size="mini" type="success" @click="onUpdateLetter(false)" v-if="type === 'project'">已有评估函在线编辑</el-button>
      <el-button size="mini" @click="onDownloadTemplate" v-if="type !== 'activity'">下载上传模板</el-button>
      <el-button size="mini" type="primary" @click="handleUploadModalVisible">上传模板数据</el-button>
    </div>

    <ex-table
      :columns="[
        ...(isSelection ? [{ type: 'selection' }] : []),
        ...(mapColumns[type || 'budget']), 
        ...(!readonly && type !== 'activity' ? [{ label: '操作', _slot_: 'action', width: '130px',fixed: 'right'}] : [])
      ]"
      @page-curr-change="handlePageChange"
      @page-size-change="handleSizeChange"
      :noPagination="noPagination"
      :page="pageInfo"
      :sizes="['15']"
      @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 ? '' :'warning'">
         {{ Number(scope.row.is_check) === mapCheck[type || 'budget'].ok  ?  "已选择" : "未选择" }}
        </el-tag>
      </template>

      <template #status="{scope}">
        <el-tag size="mini" :type="Number(scope.row.status) === 2 ? '' :'info'">
          {{(statusOptions.find(({value}) => Number(scope.row.status) === value) || {}).label || '--'}}
        </el-tag>
      </template>

      <template #action="{ scope }">
        <!-- 选中时不能取消发布 -->
        <el-button 
          size="mini" 
          type="text" 
          @click="onPublish(scope.row)">
          {{Number(scope.row.status) === 1 ? '发布' : '取消发布'}}
        </el-button>

        <!-- 发布或选中的函无法删除编辑 -->
        <el-button 
          v-if="
            (type !== 'activity' 
            && (Number(scope.row.is_check) !== mapCheck[type].ok) 
            && Number(scope.row.status) !== 2) || type === 'settlement'" 
            type="text" 
          size="mini" 
          @click="linkToLetterUpdate(scope.row)"
        >编辑</el-button>

        <el-button 
          v-if="type === 'budget' && Number(scope.row.is_check) !== mapCheck[type].ok && Number(scope.row.status) !== 2" 
          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)"
      @abnormal="abnormal"
      :isFile="isFile"
      :title="title" 
      :type="type"
      :id="id"
    />

    <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 { template ,mapLetterToType } from "./_template"
import mixinPage from "@/mixins/elPaginationHandle";
import { writeFile, utils } from "xlsx";

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'
      },
      statusOptions:[
        { value:1,label:'草稿'},
        { value:2,label:'已发布'}
      ],
      noPagination:false,
      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  })
      )

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

      this.updateLoading(false)

      if(letter.code === 0){
        this.abnormal()
      }

      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)
    },
    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
    },

    abnormal(){
      this.$emit('abnormal')
    },
    async onPublish(row){
      if(Number(row.is_check) === 1 && this.type !== 'settlement'){
        this.$message.warning('当前预算函已经被选中,无法取消发布!')
        return
      }

      const { status, id } = row
      this.loading = true

      const baseMsg = `${mapTitle[this.type]} ${row.planCode}`
      
      const message = Number(status) === 1 
      ? `确认发布${baseMsg}?`
      : `确认将${baseMsg} 恢复为草稿`

      this.$confirm(message,{
        type:'warning'
      }).then(async () => {
        this.loading = true
        const { code } = await asyncRequest.status({
          id:[id],
          status:Number(status) === 1 ? 2 : 1
        })
        this.loading = false

        if(code !== 1) return

        const message = Number(status) === 1 
          ? `${baseMsg} 发布成功`
          : `${baseMsg} 恢复草稿成功`

        
        if(Number(status) === 1){
          this.$emit('publish-ok')
        }

      this.$message.success(message)

        this.searchList()
      })
    },

    async searchList(){
      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.noPagination = Number(data.count) <= 15
      this.pageInfo.total = Number(data.count)
    }
  }
}
</script>

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