<template>
  <a-modal
    :title="title"
    :width="width"
    :visible="visible"
    :bodyStyle="bodyStyle"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">


          <a-form-item label="外包合同" :labelCol="labelCol" :wrapperCol="wrapperCol" :required="true">
            <j-dict-select-tag  v-decorator="['subcontractType', validatorRules.subcontractType]"  :type="'list'" @change="selectSubcontractType" placeholder="请选择外包合同方式" :triggerChange="true" dictCode="subcontract_type"/>
          </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="fileList1"
              :beforeUpload="beforeUpload1"
              @change="handleChange1">
              <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 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'
  import { getAction, deleteAction, putAction, postAction,downFile } from '@/api/manage'
  import pick from 'lodash.pick'


  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: "UploadSubcontractorContractModal",
    components: {
      JDate,
      JUpload,
      JSelectDepart,
      JDictSelectTag,
    },
    data () {
      return {
        form: this.$form.createForm(this),
        uploadAction: window._CONFIG['domianURL'] + '/hpSys/common/ossUpload',
        urlDownload: window._CONFIG['domianURL'] + '/hpSys/common/ossDownload',
        fileList1: [],
        defaultFileList:[],
        accept:'.pdf',
        title:"操作",
        width:1000,
        bodyStyle: {
          paddingTop: '20px',
          paddingBottom:'50px',
          maxHeight: (window.innerHeight * 0.64) + 'px',
          'overflow-y': 'auto'
        },
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },

        confirmLoading: false,
        validatorRules:{
        subcontractType:{rules: [{ required: true, message: '请输入外包合同类型' }]},
        subcontract:{rules: [{ required: true, message: '请输入外包合同!' }]},
        },
        url: {
          fileUpload: window._CONFIG['domianURL'] + '/hpSys/common/ossUpload',
          // add: "/saasmanager/hwSubcontractorContract/add",
          edit: '/requiremanager/hwRequirement/edit',
          imgerver: window._CONFIG['imgDomainOssURL'],
        }
     
      }
    },
    props: {
      text: {
        type: String,
        required: false,
        default: '点击上传'
      },
      fileType: {
        type: String,
        required: false,
        default: FILE_TYPE_ALL
      },
      /*这个属性用于控制文件上传的业务路径*/
      bizPath: {
        type: String,
        required: false,
        default: '/hpwork/hwcompany'
      },
      value: {
        type: String,
        required: false
      },
      //此属性被废弃了
      triggerChange: {
        type: Boolean,
        required: false,
        default: false
      }
    },
    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;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'subcontractorId','subcontractType','subcontract'))
          this.form.setFieldsValue({ subcontractType:this.model.subcontractType!=null?String(this.model.subcontractType):''})
        })
        this.editFileList1(this.model.subcontract)
      },
      close () {
        this.$emit('close');
        this.visible = false;
      },
      handleOk () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            let formData = Object.assign(this.model, values);
            console.log("表单提交数据",formData)
            httpAction(httpurl,formData,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()
      },

      selectSubcontractType(e){
        if(e!=null && e!=''){
          this.form.setFieldsValue({ subcontractType:e})
        }
        var subcontractType = this.form.getFieldValue('subcontractType');
        this.model.subcontractType=subcontractType==''?null:subcontractType
      },

      //上传文件
      handlePathChange1() {
        let uploadFiles = this.fileList1
        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)
        console.log(2222,this.fileList1)
      },
      beforeUpload1(file) {
        if (this.fileList1.length>=1) {
          this.$message.warning('只能上传一个文件')
          return false
        }
      },
      handleChange1(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 fileList1 = info.fileList
        if (info.file.status === 'done') {
          if (info.file.response.success) {
            fileList1 = fileList1.map((file) => {
              if (file.response) {
                // file.url = this.urlDownload+file.response.message;
                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.fileList1 = fileList1
        if (info.file.status === 'done' || info.file.status === 'removed') {
          this.handlePathChange1()
        }
      },
      //回显文件所用
      editFileList1(paths) {
        if (!paths || paths.length == 0) {
          //return [];
          // update-begin- --- author:os_chengtgen ------ date:20190729 ---- for:issues:326,Jupload组件初始化bug
          this.fileList1 = []
          return
          // update-end- --- author:os_chengtgen ------ date:20190729 ---- for:issues:326,Jupload组件初始化bug
        }
        let fileList1 = []
        let arr = paths.split(',')
        for (var a = 0; a < arr.length; a++) {
          fileList1.push({
            uid: uidGenerator(),
            name: getFileName(arr[a]),
            status: 'done',
            url: this.url.imgerver +  arr[a],
            thUrl: arr[a]
          })
        }
        this.fileList1 = fileList1
      },
      handleDelete(file) {
        //如有需要新增 删除逻辑
        console.log(file)
        this.fileList = [];
      },

    }
  }
</script>