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




        <a-form-item label="服务费率" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input-number :min="0.01" :max="99.99" v-decorator="[ 'serviceRate', validatorRules.serviceRate]"
                          :formatter="value => `${value}%`" :parser="value => value.replace('%', '')" :precision="2"
                          placeholder="请输入服务费率"
                          style="width: 100%"/>
        </a-form-item>


        <a-form-item label="转包合同" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-upload
            name="file"
            :multiple="true"
            :remove="handleDelete"
            :action="uploadAction"
            :headers="headers"
            :data="{'isup':1,'bizPath':bizPath}"
            :fileList="fileList"
            :beforeUpload="beforeUpload"
            @change="handleChange">
            <a-button> <a-icon type="upload" /> 选择上传 </a-button>
          </a-upload>
        </a-form-item>


        <a-form-item label="生效时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <j-date placeholder="请选择开始时间" v-decorator="[ 'startDate', validatorRules.startDate]" :trigger-change="true" style="width: 100%"/>
        </a-form-item>

        <a-form-item label="结束时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <j-date placeholder="请选择结束时间" v-decorator="[ 'endDate', validatorRules.endDate]" :trigger-change="true" style="width: 100%" />
        </a-form-item>

      </a-form>
    </a-spin>

  </j-modal>
</template>

<script>
  import Vue from 'vue'
  import { httpAction,getAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import { validateDuplicateValue } from '@/utils/util'
  import JDate from '@/components/jeecg/JDate'
  import SubcontractorSelectWindowInCondition from '../../hlwsubcontractor/modules/SubcontractorSelectWindowInCondition'
  import { ACCESS_TOKEN } from '@/store/mutation-types'
  const validateTime = (params) => getAction('/wisdom/hlwCpSubcontractor/validateTime', params)


  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: "HlwCpSubcontractorModal",
    components: {
      SubcontractorSelectWindowInCondition,
      JDate,
    },
    data () {
      return {
        headers: {},
        fileList: [],
        form: this.$form.createForm(this),
        title:"操作",
        width:800,
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
          subcontractorId:{rules: [{ required: true, message: '请选择服务商!' }]},
          serviceRate: {
            rules: [
              { required: true, message: '请输入服务费率!'},
            ]
          },
          createTime: {
            rules: [
              { required: true, message: '请输入创建时间!'},
            ]
          },
          startDate: {
            rules: [
              { required: true, message: '请输入开始时间!'},{ validator: this.validateTime }
            ]
          },
          endDate: {
            rules: [
              { required: true, message: '请输入结束时间!'}
            ]
          },
          createBy: {
            rules: [
              { required: true, message: '请输入创建者!'},
            ]
          },
        },
        url: {
          add: "/wisdom/hlwCpSubcontractor/add",
          edit: "/wisdom/hlwCpSubcontractor/edit",
          imgerver: window._CONFIG['imgDomainOssURL'],
          fileUpload: window._CONFIG['domianURL'] + '/hpSys/common/ossUpload',
        }
      }
    },
    props: {
      fileType: {
        type: String,
        required: false,
        default: FILE_TYPE_ALL
      },
      /*这个属性用于控制文件上传的业务路径*/
      bizPath: {
        type: String,
        required: false,
        default: '/hlwCpSubcontractor/hlwSubContract'
      },
    },
    created () {
      const token = Vue.ls.get(ACCESS_TOKEN)
      this.headers = { 'X-Access-Token': token }
    },
    computed: {
      uploadAction: function() {
        return this.url.fileUpload
      }
    },
    methods: {
      add () {
        this.edit({});
      },
      edit (record) {
        this.form = this.$form.createForm(this)
        this.model = Object.assign({}, record);
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'cpId','subcontractorId','serviceRate','createTime','createBy','updateTime','updateBy','hlwSubcontractorName',"startDate","endDate","subcontract"))
        })
        this.editFileList(this.model.subcontract)
      },
      close () {
        this.$emit('close');
        this.visible = false;
      },
      handleOk () {
        this.endDate=this.form.getFieldValue('endDate')
        this.startDate=this.form.getFieldValue('startDate')
        if(new Date(this.endDate).getTime()<=new Date(this.startDate).getTime()){
          this.$message.warning('结束时间必须大于开始时间')
          return
        }
        const that = this;
        const { fileList } = that
        // 触发表单验证
        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);
            let isDone = true;
            var subcontract = "";
            fileList.forEach((file,index) => {
              if(!file.thUrl){
                isDone = false;
              }
              if(index === 0){
                subcontract = file.thUrl;
              }else{
                subcontract += "," + file.thUrl;
              }
            });
            //上传文件出错
            if(!isDone){
              that.$message.error("正在上传，请稍后提交!");
              that.confirmLoading = false
              return;
            }
            formData.subcontract = subcontract;
            formData.subcontractorId = this.model.subcontractorId;

            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()
      },
      popupCallback(row){
        this.form.setFieldsValue(pick(row,'cpId','subcontractorId','serviceRate','createTime','createBy','updateTime','updateBy'))
      },






      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: function(file) {
        //TODO 验证文件大小
      },

      handleChange(info) {
        let fileList = info.fileList
        if (info.file.status === 'done') {
          if (info.file.response.success) {
            fileList = fileList.map((file) => {
              if (file.response) {
                file.url = this.url.imgerver + file.response.message
                file.thUrl = 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
      },

      //移除文件
      handleDelete(file){
        const index = this.fileList.indexOf(file);
        const newFileList = this.fileList.slice();
        newFileList.splice(index, 1);
        this.fileList = newFileList;
      },


      //回显文件所用
      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.url.imgerver +  arr[a],
            thUrl: arr[a]
          })
        }
        this.fileList = fileList
      },

      validateTime(rule,value,callback){
        var   model= this.model
        model.startDate=value
        validateTime(model).then((res) => {
          if (res.success) {
            callback();
          } else {
            callback("有效期存在重叠!");
          }
        })
      },

      
    }
  }
</script>