/*
 * @Author: Anmin 
 * @Email:changanmin1@crc.com.hk 
 * @Date: 2018-08-25 11:36:28 
 * @Last Modified by: Anmin
 * @Last Modified time: 2018-12-06 16:24:53
 * @Module 手工增加 Excel 导入界面
 */ 
<template>
<div style="padding:10px">
  <Row gutter="10">
    <Col span="12">
    <Card bordered>
      <p slot="title">
        <Icon type="ios-cloud-download"></Icon>
        模板下载
      </p>
      <Form :label-width="120" inline>
        <FormItem label="选择导入公司模板">
          <!-- <Select multiple transfer
                      style="width:260px"
                        v-model="compCode"
                        :loading="select_loading"
                        size="small"
                        filterable
                        clearable
                        
                      >
                  <Option v-for="(option, index) in ouNameList" :value="option.companyCode" :key="index">{{option.ouName}}</Option>
              </Select> -->
          <!-- @on-change="handle_saveComp" -->
          <SelectCompany 
            placeholder="请选择公司模板"
            :flag="true"
            multiple
            filterable
            clearable  
            transfer
            v-model="compCode"
          ></SelectCompany>
        </FormItem>
        <FormItem>
          <Button icon="arrow-down-a" type="info" :loading="loading_down" @click="download">下载模板</Button>
        </FormItem>
      </Form>
    </Card>
    </Col>
    <Col span="12">
    <Card bordered>
      <p slot="title">
        <Icon type="ios-cloud-upload"></Icon>
        上传文件
      </p>
      <Upload
        :action="uploadUrl"
        :data="fileData" 
        :headers="headers"
        :before-upload="beforeUpload"
        accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel.sheet.macroEnabled.12"
        :on-success="onSuccess"
        :on-error="onError"
      >
        <Button type="success" icon="ios-cloud-upload-outline">选择文件</Button>
      </Upload>
    </Card>
    </Col>
  </Row>
  <Row style="margin-top:10px;">
    <Col>
    <Card>
      <p slot="title">
        收款导入信息
      </p>
      <EMSTable
        ref="fileTable"
        :server="server" 
        :columnsFn="getColumns"
        :params="tableParams"
        :highlight-row="true"
        action="loadFileMsg"
      ></EMSTable>
    </Card>
    </Col>
  </Row>
</div>
</template>

<script>
import Server from "./server.js";
import {
  EMSTable,
  SelectCompany
} from "ems-components";

import {
  exportFile
} from '../receivableComponent/exportFile.js'
const server = new Server(); 
export default {
  components: {
    EMSTable,
    SelectCompany
  },
  props: {
    title: {
      type: String,
      default: "",
    }
  },
  mounted() { 
    this.$emit("SetTitle", this.title);
  },
  data() {
    //定义 上传文件路径
    const uploadUrl = `${process.env.API.emsReceivable}/receivableExcel/excelImportHandworkReceivable`;
    let crctoken  = sessionStorage.crctoken;//$axios.defaults.headers.crctoken 
    return { 
      headers:{
        'crctoken':crctoken
      },
      compCode: "", //选择的公司
      server: server, 
      uploadUrl: uploadUrl,
      fileData: {
        name: 'RECEIVABLES'
      },
      tableParams: {
        uploadFun:"1"
      },
      loading_down:false, 
    }
  },
  methods: {  
    beforeUpload(file) { 
      let isExcel = file.type === 'application/vnd.ms-excel' ? true :  file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ? true : file.type === 'application/vnd.ms-excel.sheet.macroEnabled.12'?true:false;
      //如果遇到获取type为空时取后缀名进行判断是否是xls、xlsx、xlsm
      if(file.type == ""){
        if((file.name.split("."))[file.name.split(".").length-1] == "xls" || 
          (file.name.split("."))[file.name.split(".").length-1] == "xlsx" ||
          (file.name.split("."))[file.name.split(".").length-1] == "xlsm"){
          isExcel = true;
        }
      }
      const isLt2M = file.size / (1024*1024) <= 10;
      if (!isExcel) {
        this.$Message.error('上传文件不是Excel格式!');
      }
      if (!isLt2M) {
        this.$Message.error('上传文件大小不能超过10MB!');
      }
      return isExcel && isLt2M;
    },
    async onSuccess(response, file, fileList) {
      console.info(response, file, fileList);
      //上传成功 刷新表格 
      this.$refs["fileTable"].load(this.tableParams, 1);
    },
    onError(error, file, fileList) {
      this.$refs["fileTable"].load(this.tableParams, 1);
    },
    async download() {
      this.loading_down = true;
      if(this.compCode.length <= 0){
        this.loading_down = false;
        return this.$Message.error('请至少选择一家公司的模板下载!');
      }else{ 
        let params = {
          ouCodeListStr:this.compCode.join(',')
        }
        let result = await this.server.downloadTemplate(params);
        if (result.statusCode === "-1") {
          this.$Message.error(result.msg || "模板文件下载失败"); 
          this.loading_down = false;
        } else { 
          this.loading_down = false;
          exportFile(result);
        }
      }
    }, 
    downloadErrorInfo(row) {
      //下载 报错文件 
      this.server.loadFileError(row.id);  
    },
    getColumns() {
      return [{
          title: "上传日期",
          align: "center",
          key: "createdTime",
          minWidth: 100
        },
        {
          title: "状态",
          align: "center",
          key: "status",
          minWidth: 50,
          render: (h, params) => {
            // 上传状态 1处理中 2已成功 3已失败

            let status = +params.row.status;
            let val = '处理中';
            if (status === 1) {
              val = '处理中'
            } else if (status === 2) {
              val = "已成功"
            } else if (status === 3) {
              val = "已失败"
            }
            return h(
              "div", {
                attrs: {
                  class: "ivu-table-cell ivu-table-cell-ellipsis",
                  title: val
                }
              },
              val
            );
          }
        },
        {
          title: "描述",
          align: "center",
          key: "remark",
          minWidth: 250,
          render: (h, params) => {
            // 上传状态 1处理中 2已成功 3已失败

            let val = params.row.remark;
            return h(
              "div", {
                attrs: {
                  class: "ivu-table-cell ivu-table-cell-ellipsis",
                  title: val
                }
              },
              val
            );
          }
        },
        {
          title: "报错信息",
          align: "center",
          key: "status",
          minWidth: 100,
          render: (h, params) => {
            let vm = this;
            if (+params.row.status === 3 && params.row.errorFilePath != null) {
              return h(
                "Button", {
                  props: {
                    type: 'text',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      vm.downloadErrorInfo(params.row);
                    }
                  }
                },
                '报错信息'
              );
            } else {
              return h('div', {}, '');
            }
          }
        }
      ];
    }
  }
}
</script>
