<template>
  <a-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form" style="padding-bottom: 30px;padding-top: 30px">

        <a-form-item label="合同类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <j-dict-select-tag type="list" @change="getcontractType"
                             v-decorator="['subcontractType',validatorRules.subcontractType]" :trigger-change="true"
                             dictCode="subcontract_type" placeholder="请选择合同方式"/>
        </a-form-item>

        <template v-if="model.subcontractType=='0'">
          <a-form-item label="选择合同" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-upload
              name="file"
              :accept="accept"
              :multiple="false"
              :action="uploadAction"
              :headers="headers"
              :data="{'isup':1,'bizPath':bizPath}"
              :fileList="fileList"
              :beforeUpload="beforeUpload"
              @change="handleChange">
              <a-button>
                <a-icon type="upload"/>
                {{ text }}
              </a-button>
              <span style="margin-left: 10px">请上传pdf格式</span>
            </a-upload>
          </a-form-item>
        </template>

      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>

  import { httpAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import JDate from '@/components/jeecg/JDate'
  import JUpload from '@/components/jeecg/JUpload'
  import JSelectDepart from '@/components/jeecgbiz/JSelectDepart'
  import JDictSelectTag from '@/components/dict/JDictSelectTag'
  import Vue from 'vue'
  import { ACCESS_TOKEN } from '@/store/mutation-types'

  const FILE_TYPE_ALL = "all"
  const FILE_TYPE_PDF = 'pdf'
  const uidGenerator = () => {
    return '-' + parseInt(Math.random() * 10000 + 1, 10)
  }
  const getFileName = (path) => {
    if (path.lastIndexOf('\\') >= 0) {
      let reg = new RegExp('\\\\', 'g')
      path = path.replace(reg, '/')
    }
    return path.substring(path.lastIndexOf('/') + 1)
  }

  export default {
    name: 'HwViewSubcontractModal',
    components: {
      JDate,
      JUpload,
      JSelectDepart,
      JDictSelectTag
    },
    data() {
      return {
        uploadAction: window._CONFIG['domianURL'] + '/hpSys/common/ossUpload',
        urlDownload: window._CONFIG['domianURL'] + '/hpSys/common/ossDownload',
        headers: {},
        fileList: [],
        form: this.$form.createForm(this),
        title: '操作',
        width: 600,
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        options: [{
          value: '',
          label: '',
          isLeaf: false
        }],
        accept:'.pdf',
        confirmLoading: false,
        validatorRules: {
          subcontractType: { rules: [{ required: true, message: '请输入合同方式' }] },
          subcontract: {},
        },
        url: {
          fileUpload: window._CONFIG['domianURL'] + '/hpSys/common/ossUpload',
          edit: '/requiremanager/hwRequirement/editContract'
        }

      }
    },
    props: {
      text: {
        type: String,
        required: false,
        default: '点击上传'
      },
      fileType: {
        type: String,
        required: false,
        default: FILE_TYPE_ALL
      },
      /*这个属性用于控制文件上传的业务路径*/
      bizPath: {
        type: String,
        required: false,
        default: '/hpwork/hworder'
      },
      value: {
        type: String,
        required: false
      },
      //此属性被废弃了
      triggerChange: {
        type: Boolean,
        required: false,
        default: false
      }
    },
    watch: {
      value(val) {
        this.initFileList(val)
      }
    },
    created() {
      const token = Vue.ls.get(ACCESS_TOKEN)
      this.headers = { 'X-Access-Token': token }

    },
    methods: {
      add() {
        this.edit({})
      },
      edit(record) {
        this.form.resetFields()
        this.model = Object.assign({}, record)
        this.visible = true
        console.log("ddd",record)
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, 'subcontract'))
          this.form.setFieldsValue({ subcontractType:this.model.subcontractType!=null?String(this.model.subcontractType):''})
        })
        //回显文件
        this.editFileList(this.model.subcontract)
      },
      close() {
        this.$emit('close')
        this.visible = false
      },
      handleOk() {
        // if(this.model.subcontractType == 0) {
        //   if (!this.model.subcontract || this.fileList.length == 0) {
        //     this.$message.warning('请上传企业合同')
        //     return
        //   }
        // }


        const that = this
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true
            let httpurl = ''
            let method = ''
            httpurl += this.url.edit
            method = 'put'
            let formData = Object.assign(this.model, values)
            console.log('表单提交数据', formData)
            this.model.subcontract=this.model.subcontractType!=0?null: this.model.subcontract
            httpAction(httpurl, {id:this.model.id,subcontract:this.model.subcontract,subcontractType:this.model.subcontractType}, method).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            }).finally(() => {
              that.confirmLoading = false
              that.close()
            })
          }

        })
      },
      handleCancel() {
        this.close()
      },
      popupCallback(row) {
        this.form.setFieldsValue(pick(row, 'subcontract'))
      },


      //回显文件所用
      editFileList(paths) {
        if (!paths || paths.length == 0) {
          //return [];
          // update-begin- --- author:os_chengtgen ------ date:20190729 ---- for:issues:326,Jupload组件初始化bug
          this.fileList = []
          return
          // update-end- --- author:os_chengtgen ------ date:20190729 ---- for:issues:326,Jupload组件初始化bug
        }
        let fileList = []
        let arr = paths.split(',')
        for (var a = 0; a < arr.length; a++) {
          fileList.push({
            uid: uidGenerator(),
            name: getFileName(arr[a]),
            status: 'done',
            url: this.urlDownload + '?fileName=' + arr[a],
          })
        }
        this.fileList = fileList
      },
      //上传文件所用
      initFileList(paths) {
        if (!paths || paths.length == 0) {
          //return [];
          // update-begin- --- author:os_chengtgen ------ date:20190729 ---- for:issues:326,Jupload组件初始化bug
          this.fileList = []
          return
          // update-end- --- author:os_chengtgen ------ date:20190729 ---- for:issues:326,Jupload组件初始化bug
        }
        let fileList = []
        let arr = paths.split(',')
        for (var a = 0; a < arr.length; a++) {
          fileList.push({
            uid: uidGenerator(),
            name: getFileName(arr[a]),
            status: 'done',
            url: this.urlDownload + '?fileName=' + arr[a],
            response: {
              status: 'history',
              message: arr[a]
            }
          })
        }
        this.fileList = fileList
      },
      handlePathChange() {
        let uploadFiles = this.fileList
        let path = ''
        if (!uploadFiles || uploadFiles.length == 0) {
          path = ''
        }
        let arr = []

        for (var a = 0; a < uploadFiles.length; a++) {
          arr.push(uploadFiles[a].response.message)
        }
        if (arr.length > 0) {
          path = arr.join(',')
        }
        this.$emit('change', path)
      },
      beforeUpload(file) {
        if (this.fileList.length>=1) {
          this.$message.warning('只能上传一个文件')
          return false
        }
      },
      handleChange(info) {
        console.log(info)
        if (info.fileList.length>1) {
          return false
        }
        var fileType =info.file.type
        if(fileType){
          if (fileType.indexOf(FILE_TYPE_PDF)<0) {
            this.$message.warning('请上传pdf文件')
            return false

          }
        }
        console.log('--文件列表改变--')
        let fileList = info.fileList
        if (info.file.status === 'done') {
          if (info.file.response.success) {
            fileList = fileList.map((file) => {
              if (file.response) {
                this.model.subcontract = file.response.message
              }
              return file
            })
          }
          this.$message.success(`${info.file.name} 上传成功!`)
        } else if (info.file.status === 'error') {
          this.$message.error(`${info.file.name} 上传失败.`)
        } else if (info.file.status === 'removed') {
          this.handleDelete(info.file)
        }
        this.fileList = fileList
        if (info.file.status === 'done' || info.file.status === 'removed') {
          this.handlePathChange()
        }
      },
      handleDelete(file) {
        //如有需要新增 删除逻辑
        console.log("ss",file)
        this.fileList = [];
      },
      getcontractType(val) {
        this.model.subcontractType = val
      },

    }
  }
</script>