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

        <a-form-item label="用户合同" :labelCol="labelCol" :wrapperCol="wrapperCol" :required="true">
          <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>

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

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

          <a-form-item label="自动续约" :labelCol="labelCol"  :wrapperCol="wrapperCol">
            <a-radio-group buttonStyle="outline" @change="changeAutoRenew" v-decorator="[ 'isAutoRenew', {'initialValue':1}]">
              <a-radio :value="1">是</a-radio>
              <a-radio :value="0">否</a-radio>
            </a-radio-group>
          </a-form-item>

          <div style="color:#E70000;font-size: 12px;padding-left: 11%">
            温馨提示：<br/>
            <div style="margin-top: 12px;padding-left: 20px;color:#E70000">1、请确认此处选择的“开始/结束时间”与真实合同保持一致</div><br/>
            <div style="padding-left: 20px;color:#E70000">2、新上传合同与已上传老合同时间不能重叠</div><br/>
            <div style="padding-left: 20px;color:#E70000">3、请在时间上尽量保持新上传合同与上一份合同相互连续</div>
          </div>
        </template>

      </a-form>
    </a-spin>
    <div class="drawer-bootom-button" v-show="!disableSubmit">
      <a-button class="ant-btn ant-btn-primary" style="margin-left: 8px"  @click="handleOk">保存</a-button>
    </div>

  </a-modal>
</template>

<script>

  import Vue from 'vue'
  import { ACCESS_TOKEN } from '@/store/mutation-types'
  import { httpAction,getAction, deleteAction, putAction, postAction,downFile } from '@/api/manage'
  import JUpload from '@/components/jeecg/JUpload'
  import pick from 'lodash.pick'
  import JDate from '@/components/jeecg/JDate'
  import moment from "moment"

  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: "HwOrderUploadContractModal ",
    components: {
      JDate
    },
    data () {
      return {
        plainOptions:[],
        valueInfo:[],
        headers: {},
        fileList: [],
        form: this.$form.createForm(this),
        title:"操作",
        modelStyle: {
          width: '52%',
          style: { top: '20px' },
          fullScreen: false
        },
        bodyStyle: {
          paddingTop: '20px',
          paddingBottom:'50px',
          height: (window.innerHeight * 0.6) + 'px',
          'overflow-y': 'auto'
        },
        disableSubmit:false,
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        selectedDepartKeys:[], //保存用户选择服务商id
        checkedDepartKeys:[],
        confirmLoading: false,
        validatorRules:{
          workContract:{},
          startDate: { rules: [{ required: true, message: '请选择合同开始时间' }] },
          endDate: { rules: [{ required: true, message: '请选择合同结束时间' }] }
        },
        url: {
          add: '/ordermanager/hwOrder/editContract',
          fileUpload: window._CONFIG['domianURL'] + '/hpSys/common/ossUpload',
          imgerver: window._CONFIG['imgDomainOssURL'],
          getOneYearLaterTime:"/ordermanager/hwOrder/getOneYearLaterTime",
        }
     
      }
    },
    props: {
      fileType: {
        type: String,
        required: false,
        default: FILE_TYPE_ALL
      },
      /*这个属性用于控制文件上传的业务路径*/
      bizPath: {
        type: String,
        required: false,
        default: '/hpwork/hworder'
      },
    },
    created () {
      const token = Vue.ls.get(ACCESS_TOKEN)
      this.headers = { 'X-Access-Token': token }
    },
    computed: {
      uploadAction: function() {
        return this.url.fileUpload
      }
    },
    methods: {
      add (record) {
        this.edit(record);
      },
      edit (record) {
        this.form = this.$form.createForm(this)
        this.form.resetFields();
        this.model={}
        this.model = Object.assign({}, record);
        if(this.model.isAutoRenew==undefined){
          this.model.isAutoRenew = 1
        }
        console.log(this.model)
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'startDate','endDate','isAutoRenew'))
          if(!this.model.contractId){
            this.form.setFieldsValue({ startDate:  moment(new Date()).format('YYYY-MM-DD') })
            this.getOneYearLaterTime(moment(new Date()).format('YYYY-MM-DD'))
          }
        })
        this.editFileList(this.model.workContract)
      },

      getOneYearLaterTime(time){
        getAction(this.url.getOneYearLaterTime,{startDate:time}).then((res)=>{
          if (res.success) {
            this.$nextTick(() => {
              this.form.setFieldsValue({ endDate:  res.result })
            })
          }
        })
      },

      close () {
        this.$emit('ok');
        this.visible = false;
      },
      modalFormOk(){

      },
      handleCancel(){
        this.$emit('ok');
        this.close()
      },
      handleOk () {
        const that = this;
        const { fileList } = that
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            httpurl+=this.url.add;
            let method = 'post';
            var workContract = "";
            let formData = Object.assign(this.model, values);
            let isDone = true;
            fileList.forEach((file,index) => {
              if(!file.thUrl){
                isDone = false;
              }
              if(index === 0){
                workContract = file.thUrl;
              }else{
                workContract += "," + file.thUrl;
              }
            });
            //上传文件出错
            if(!isDone){
              that.$message.error("正在上传，请稍后提交!");
              that.confirmLoading = false
              return;
            }
            if(!workContract ||  workContract==""){
              that.$message.error("请先上传合同!");
              that.confirmLoading = false
              return;
            }
            if(this.form.getFieldValue('endDate')<this.form.getFieldValue('startDate')){
              that.$message.error("合同结束时间需大于开始时间!");
              that.confirmLoading = false
              return;
            }
            formData.workContract = workContract;
            console.log("表单提交数据",formData)
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
                that.close();
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
         
        })
      },


      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)
        console.log(1111,this.fileList)
      },



      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{
            //后台返回失败
            this.$error({
              title: '失败',
              content: '文件上传失败',
            });
          }
        }else if (info.file.status === 'error') {
          this.$error({
            title: '失败',
            content: '文件上传失败',
          });
        } 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.getAvatarView(arr[a]),
            thUrl: arr[a]
          })
        }
        this.fileList = fileList
      },

      getAvatarView(idcardPicture) {
        if( idcardPicture.indexOf("http")!=-1){
          return idcardPicture
        }else{
          return this.url.imgerver+idcardPicture
        }
      },

      handleDateChange1(time){
        this.getOneYearLaterTime(time)
      },
      changeAutoRenew(e){
        if(e.target.value==0){
          if(this.form.getFieldValue("startDate")){
            this.getOneYearLaterTime(moment(this.form.getFieldValue("startDate")).format('YYYY-MM-DD'))
          }
        }
        this.model.isAutoRenew=e.target.value

      }

    }
  }
</script>
<style>
  .drawer-bootom-button {
    position: absolute;
    bottom: -8px;
    width: 100%;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    left: 0;
    background: #fff;
    border-radius: 0 0 2px 2px;
  }
  .avatar-uploader > .ant-upload {
    width: 104px;
    height: 104px;
  }

  .ant-upload-select-picture-card i {
    font-size: 49px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }
</style>