<template>
  <div :style="{ width: recordConfig.options.width }" :class="listClass"  style="text-align: left;">
    <a-upload
      name="file"
      :accept="accept"
      :multiple="recordConfig.options.multiple"
      :data="optionsData"
      :fileList="fileList"
      :action="uploadAction"
      :headers="headers"
      :listType="fileListType"
      @preview="handlePreview"
      @change="handleChange"
      :remove="remove"
      :beforeUpload="beforeUpload"
    >
      <a-button v-show="showButton"><ych-icon type="upload"/>{{ locleUtil.getLocale('m.common.button.upload') }}</a-button>
    </a-upload>
<!--    <a-button :disabled="itemDetail && itemDetail.disabled" type="primary" style="margin-left: 10px;" @click="saveTable"><ych-icon type="check"/>保存</a-button>-->
    <a-table
      ref="fileListTable"
      size="middle"
      bordered
      rowKey="uid"
      style="margin-top: 15px;"
      :columns="columns"
      :dataSource="fileList"
      :pagination="false"
      :loading="loading"
    >
      <template slot="filename" slot-scope="text, recordConfig">
        <a @click="handlePreview(recordConfig)">
          {{text}}
        </a>
      </template>
      <template slot="action" slot-scope="text, recordConfig">
        <a @click="deleteFile(recordConfig)" v-show="showButton">
          {{locleUtil.getLocale('m.common.button.delete')}}
        </a>
      </template>
    </a-table>
  </div>
</template>
<script>

import { getFileAccessHttpUrl, deleteAction } from '../utils/manage'
import YchConstant from "../utils/YchConstant";
import TokenStorageUtil from "../utils/TokenStorageUtil";
import locleUtil from "../utils/LocleUtil";
import LocleUtil from "../utils/LocleUtil";

export default {
  name: 'KFileUpload',
  data () {
    return {
      uploadAction: YchConstant.PREFIX_REQUEST + YchConstant.PREFIX_SYSTEM + '/common/upload',
      headers: {},
      fileList: [],
      deleteUrl: YchConstant.PREFIX_SYSTEM + '/common/deleteFile',
      defaultTableStyle:'height:200px;overflow:auto;',
      loading:false,
      isDisabledDetail: false,
      buttonDatas: {
        editableList: []
      },
      userInfo: {}
    }
  },
  props: {
    itemRow: {
      default: () => {},
      type: Object
    },
    itemDetail: {
      default: () => {},
      type: Object
    },
    // 所有配置数据
    recordConfig: {
      type: Object,
      default: () => {
      }
    },
    // 数据源
    propSource: {
      type: Array,
      required: true,
      default: () => []
    },
    // 是否禁用全部组件
    disabled: {
      type: Boolean,
      default: false
    },
    value: {
      type: String,
    },
    accept:{
      type: String,
      default:''
    },
    fileSize:{
      type: Number,
      default:0
    },
    //支持 table、text、picture、picture-card，修改default值全局生效
    listType:{
      type: String,
      default:'table'
    },
  },
  computed: {
    locleUtil() {
      return locleUtil
    },
    optionsData () {
      return {
        biz: this.recordConfig.options.bizPath || 'temp'
      }
    },
    listClass(){
      if(this.listType=='table'){
        return 'upload-fileList-table'
      }else{
        return ''
      }
    },
    fileListType(){
      if(!this.listType || this.listType=='table'){
        this.listType == 'text'
      }
    },
    columns(){
      if(this.recordConfig.options.disabled){
        return [
          {
            title: locleUtil.getLocale('m.common.label.fileName'),
            dataIndex: 'name',
            align: 'left',
            scopedSlots: { customRender: 'filename' },
          },
          {
            title: locleUtil.getLocale('m.common.label.upload_time'),
            dataIndex: 'uploadTime',
            width: 160,
            align: 'center',
          },
          {
            title: locleUtil.getLocale('m.common.label.upload_user'),
            dataIndex: 'uploadUser',
            width: 160,
            align: 'center',
          },
        ]
      }else{
        return [
          {
            title: locleUtil.getLocale('m.common.label.fileName'),
            dataIndex: 'name',
            align: 'left',
            scopedSlots: { customRender: 'filename' },
          },
          {
            title: locleUtil.getLocale('m.common.label.upload_time'),
            dataIndex: 'uploadTime',
            width: 160,
            align: 'center',
          },
          {
            title: locleUtil.getLocale('m.common.label.upload_user'),
            dataIndex: 'uploadUser',
            width: 160,
            align: 'center',
          },
          {
            title: locleUtil.getLocale('m.common.label.operate'),
            dataIndex: 'action',
            align: "center",
            width: 100,
            scopedSlots: { customRender: 'action' },
          }
        ]
      }
    },
    //控制上传按钮显隐
    showButton(){
      // 脚本控制可编辑 优先级最高
      if (this.itemRow && this.itemRow.isShowEdit) {
        return true;
      }
      /*
      * 这一步用来判断是否从台账点开或者是否开启流程（disabledDetail为true）。
      * 然后判断是待办还是已办
      */
      if (this.isDisabledDetail || !this.buttonDatas || !this.buttonDatas.currentTaskInstanceVo) {
        // 在子表
        if (this.itemDetail) {
          return !this.itemDetail.disabled
        }else{
          //在表单
          return !this.recordConfig.options.disabled
        }
      }
      const currentTaskInstanceVo = this.buttonDatas.currentTaskInstanceVo;
      const identityString =  currentTaskInstanceVo && currentTaskInstanceVo.identityString;
      // 当已办的时候
      if (identityString && identityString.indexOf('已办') !== -1) {
        return false
      }
      // 当待办的时候，走过的节点统一禁用
      const currentFormCode = this.buttonDatas.formCode;
      const stepFormCode = sessionStorage.getItem('stepFormCode');
      if (stepFormCode == currentFormCode || !stepFormCode){
        return true
      }else{
        return false
      }
    },
  },
  created() {
    console.log(this,'file-this')
    this.init();

    this.userInfo = localStorage.getItem('userInfo')
  },
  methods: {
    init() {
      const token = TokenStorageUtil.get();
      this.headers = { 'X-Access-Token': token }
      //防止undefined和其它情况JSON解析出错
      if (typeof sessionStorage.getItem('disabledDetail') !== 'undefined') {
        try {
          this.isDisabledDetail = JSON.parse(sessionStorage.getItem('disabledDetail'));
        } catch (e) {
          this.isDisabledDetail = false
        }
      }
      if (sessionStorage.getItem('buttonDatas')) {
        this.buttonDatas = JSON.parse(sessionStorage.getItem('buttonDatas'));
      }
      if (this.itemRow && this.itemDetail) {
        this.fileList = (this.itemRow[this.itemDetail.key] && JSON.parse(this.itemRow[this.itemDetail.key])) || [];
      }
    },
    saveTable() {
      this.$emit('setFieldValue',this.itemDetail.key,this.fileList.length ? JSON.stringify(this.fileList) : '',this.itemRow ? this.itemRow : this.recordConfig);
      // this.$message.success('保存成功!');
    },
    handleSelectChange () {
      setTimeout(() => {
        this.fileList = this.fileList.map(item => {
          if (typeof item.response !== 'undefined') {
            const res = item.response
            return {
              type: 'file',
              name: item.name,
              status: item.status,
              uid: item.uid,
              url: getFileAccessHttpUrl(res.message) || '',
              uploadTime:res.result || '',
              userId: this.userInfo.id || this.userInfo.userId,
              uploadUser: this.userInfo.nickname
            }
          } else {
            return {
              type: 'file',
              name: item.name,
              status: item.status,
              uid: item.uid,
              url: getFileAccessHttpUrl(item.url) || '',
              uploadTime:item.uploadTime,
              userId: this.userInfo.id || this.userInfo.userId,
              uploadUser: this.userInfo.nickname
            }
          }
        })
      }, 10)
    },
    handlePreview(file) {
      // 下载文件
      const x = new XMLHttpRequest();
      x.open("GET", getFileAccessHttpUrl(file.url || file.thumbUrl), true);
      x.responseType = 'blob';

      const token = TokenStorageUtil.get();
      x.setRequestHeader('X-Access-Token', token);

      x.onload = function (e) {
        const url = window.URL.createObjectURL(x.response);
        const a = document.createElement("a");
        a.href = url
        a.download = file.name
        a.click()
      }
      x.send();
    },
    remove (file) {
      return new Promise((resovle, reject) => {
        const that = this
        this.$confirm({
          title: locleUtil.getLocale('m.common.title.delete'),
          okText: LocleUtil.getLocale('m.common.button.ok'),
          cancelText: LocleUtil.getLocale('m.common.button.cancel'),
          content: locleUtil.getLocale('m.eform.formDesign.label.shi-fou-shan-chu-filename', [file.name]),
          onOk () {
            deleteAction(that.deleteUrl, { url: file.url }).then((res) => {
              if (res.success) {
                resovle(true)
                that.handleSelectChange()
              } else {
                that.$message.error(locleUtil.getLocale('m.common.tip.deleteFileFailed'))
                resovle(false)
              }
            })
          },
          onCancel () {
            resovle(false)
          }
        })
      })
    },
    deleteFile(file){
      const that = this;
      this.$confirm({
        title: locleUtil.getLocale('m.common.title.delete'),
        okText: LocleUtil.getLocale('m.common.button.ok'),
        cancelText: LocleUtil.getLocale('m.common.button.cancel'),
        content: locleUtil.getLocale('m.eform.formDesign.label.shi-fou-shan-chu-filename', [file.name]),
        onOk() {
          that.loading = true
          deleteAction(that.deleteUrl, {url: file.url, id: file.uid}).then((res) => {
            if (res.success) {
              let matchKey = file.uid !== undefined ? 'uid' : 'name';
              that.fileList = that.fileList.filter(item=>item[matchKey] !== file[matchKey]);
              that.handleSelectChange();
            } else {
              that.$message.error(locleUtil.getLocale('m.common.tip.deleteFileFailed'));
              let matchKey = file.uid !== undefined ? 'uid' : 'name';
              that.fileList = that.fileList.filter(item=>item[matchKey] !== file[matchKey]);
              that.handleSelectChange();
            }
          }).finally(() => {
            that.loading = false
          });
        },
        onCancel(){
        }
      });
    },
    handleChange (info) {
      // 上传数据改变时
      this.fileList = info.fileList
      if (info.file.status === 'done') {
        if (info.file.response.success) {
          this.handleSelectChange()
        } else {
          this.fileList.pop()
          this.$message.error(`${info.file.name} `+info.file.response.message);
        }
        this.loading = false
      } else if (info.file.status === 'error') {
        this.fileList.pop()
        this.$message.error(locleUtil.getLocale('m.eform.formDesign.label.infofilename-shang-chuan-shi-bai', [info.file.name]))
        this.loading = false
      }
    },
    beforeUpload (file, files) {
      console.log(file, files)
      if (files.length + this.fileList.length > this.recordConfig.options.limit) {
        this.$message.warning(locleUtil.getLocale('m.eform.formDesign.label.zui-da-shang-chuan-shu-liang-wei-thisrecordoptionslimit', [this.recordConfig.options.limit]))
        files.splice(this.recordConfig.options.limit - this.fileList.length)
        return false
      }
      //fileSize值小于等于0时不限制
      if(this.fileSize>0){
        let fileSize = this.fileSize * 1024*1024
        if(file.size>fileSize){
          this.$message.warning(locleUtil.getLocale('m.common.tip.checkFileSize',[file.name,this.fileSize]));
          files.pop();
          return false
        }
      }
      this.loading = true
    },
  }
}
</script>
<style lang="less" scoped>
.upload-fileList-table /deep/ .ant-upload-list {
  display: block;
}

.upload-fileList-table /deep/  .ant-table-placeholder{
  display: block;
}
</style>
