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

        <a-form-item label="是否通过平台" :labelCol="labelCol" :wrapperCol="wrapperCol" :required="true">
          <j-dict-select-tag type="list" v-decorator="['platType']" :disabled="disabled1"  @change="onChangeMenuType"
                              :trigger-change="true"
                             dictCode="platType" placeholder="请选是否通过平台" style="width: 100%"/>
        </a-form-item>


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

        <a-form-item label="企业合同" :labelCol="labelCol" :wrapperCol="wrapperCol" :required="true">
          <j-dict-select-tag type="list" @change="getcontractType"
                             v-decorator="['serviceContractType',validatorRules.serviceContractType]" :trigger-change="true"
                             dictCode="contract_type" placeholder="请选择企业合同方式" style="width: 100%"/>
        </a-form-item>

        <template v-if="model.serviceContractType=='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>

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

        <template v-if="platType==1">
          <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>

        <template v-if="model.subcontractType=='0' && platType==1">
          <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-item label="用户合同" :labelCol="labelCol" :wrapperCol="wrapperCol" :required="true">
          <j-dict-select-tag  v-decorator="['workContractType', validatorRules.workContractType]" placeholder="请选择用户合同方式"  :type="'list'" @change="workContractType" :triggerChange="true" dictCode="workContractType"/>
        </a-form-item>

        <a-form-item label=" " :colon="false" :labelCol="labelCol" :wrapperCol="wrapperCol" >
          <a-checkbox-group :options="[{label:'自动生成订单',value:1},{label:'自动确认订单',value:2, disabled: confirmDisabled }]"  v-model="valueInfo" @change="onChange" />
        </a-form-item>


      </a-form>
    </a-spin>
    <div class="drawer-bootom-button">
      <a-button class="ant-btn"  @click="handleCancelOut">取消</a-button>
      <a-button class="ant-btn ant-btn-primary" style="margin-left: 8px"  @click="handleOkIn">确定</a-button>
    </div>
  </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 authRequire = (params) => putAction('/requiremanager/hwRequirement/authRequire', params)
  const isDisabled = (params) => getAction('/requiremanager/hwRequirement/isDisabled', 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: 'HwRequireAuthModal',
    components: {
      JDate,
      JUpload,
      JSelectDepart,
      JDictSelectTag,
    },
    data() {
      return {
        confirmDisabled:false,
        valueInfo:[],
        disabled1:false,
        uploadAction: window._CONFIG['domianURL'] + '/hpSys/common/ossUpload',
        urlDownload: window._CONFIG['domianURL'] + '/hpSys/common/ossDownload',
        headers: {},
        fileList: [],
        fileList1: [],
        form: this.$form.createForm(this),
        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 }
        },
        defaultFileList:[],
        accept:'.pdf',
        id:0,
        platType:0,
        confirmLoading: false,
        validatorRules: {
          subcontractType: { subcontractType: [{ required: true, message: '请选择外包合同方式' }] },
          serviceFeeRate: { rules: [{ required: true, message: '请输入服务费率!' }] },
          subcontractorFeeRate: { rules: [{ required: true, message: '请输入外包服务费率!' }] },
          workContractType:{ workContractType: [{ required: true, message: '请选择用户合同方式' }] }
          ,
        },
        url: {
          fileUpload: window._CONFIG['domianURL'] + '/hpSys/common/ossUpload',
          edit: '/requiremanager/hwRequirement/edit',
          importExcelUrl: "requiremanager/hwRequirement/importExcel?id=",
          exportXlsUrl:"/requiremanager/hwRequirement/tyemplateGeneration",
          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
      }
    },
    watch: {

    },
    created() {
      const token = Vue.ls.get(ACCESS_TOKEN)
      this.headers = { 'X-Access-Token': token }

    },
    methods: {
      add() {
        this.edit({})
      },
      edit(record) {
        this.form=this.$form.createForm(this)
        this.model={}
        this.valueInfo=[]
        this.form.resetFields()
        this.confirmDisabled=false
        this.model = Object.assign({}, record)
        console.log(11111,this.model.subcontractorFeeRate)
        this.id=record.id
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'serviceFeeRate','serviceContractType','serviceContract','subcontractorFeeRate','subcontractType','subcontract','workContractType','isAutoOrder','isAutoConfirm'))
          this.form.setFieldsValue({ platType:this.model.subcontractType!=null?'1':'2' })
          this.form.setFieldsValue({ serviceContractType:this.model.serviceContractType!=null?String(this.model.serviceContractType):''})
          this.form.setFieldsValue({ subcontractType:this.model.subcontractType!=null?String(this.model.subcontractType):''})
          this.form.setFieldsValue({ workContractType:this.model.workContractType!=null?String(this.model.workContractType):''})
        })
        this.editFileList(this.model.serviceContract)
        this.editFileList1(this.model.subcontract)
        this.platType=this.model.subcontractType!=null?1:2;
        this.model.platType=this.model.subcontractType!=null?1:2;
        if(this.model.isAutoOrder==1){
          this.valueInfo.push(1)
        }
        if(this.model.isAutoConfirm==1){
          this.valueInfo.push(2)
        }
        if(this.model.workContractType==2){
          this.confirmDisabled=true
          if(this.model.isAutoOrder==1){
            this.valueInfo=[1]
          }else{
            this.valueInfo=[]
          }
        }
        //需求下是否存在订单（需求设置页面部分参数是否可以修改）
        isDisabled({ requirementId: record.id}).then((res) => {
            this.disabled1=res
        })

        this.visible = true
      },




      close() {
        this.$emit('ok')
        this.visible = false
      },
      handleOk(){
        this.close()
      },
      handleOkIn() {
        if(!this.model.platType){
          this.$message.warning('请选择是否通过平台')
          return
        }
        if(this.model.serviceContractType!=0 && this.model.serviceContractType!=1 && this.model.serviceContractType!=2){
          this.$message.warning('请选择企业合同方式')
          return
        }
        if((this.model.subcontractType!=0 && this.model.subcontractType!=1 && this.model.subcontractType!=2) && this.platType==1){
          this.$message.warning('请选择外包合同方式')
          return
        }
        if(this.model.workContractType!=0  && this.model.workContractType!=1 && this.model.workContractType!=2){
          this.$message.warning('请选择用户合同方式')
          return
        }
        this.form.validateFields((err, values) => {
          if (!err) {
            let formData = Object.assign(this.model, values)
            formData.serviceContract=this.model.contractType!=0?null: formData.serviceContract
            formData.subcontract=this.model.subcontractType!=0?null: formData.subcontract
            authRequire(formData).then((res) => {
              if (res.success) {
                this.$message.success(res.message)
                this.$emit('ok')
                this.visible = false
              } else {
                this.$message.warning(res.message)
              }
            })
          }
        })
      },
      handleCancel(){
        this.visible = false
      },
      handleCancelOut() {
      this.close()
      },
      popupCallback(row) {
        this.form.setFieldsValue(pick(row,'subcontractType','subcontract'))
      },
      onChangeMenuType(e) {
        this.platType=e
        this.model.platType=e
        this.model.subcontractType=null
      },
      selectSubcontractType(e){
        if(e!=null && e!=''){
          this.form.setFieldsValue({ subcontractType:e})
        }
        var subcontractType = this.form.getFieldValue('subcontractType');
        this.model.subcontractType=subcontractType==''?null:subcontractType
      },
      workContractType(e){
        if(e!=null && e!=''){
          this.form.setFieldsValue({ workContractType:e})
        }
        var workContractType = this.form.getFieldValue('workContractType');
        this.model.workContractType=workContractType==''?null:workContractType
        if(this.model.workContractType==2){
          this.confirmDisabled=true
          if(this.model.isAutoOrder==1){
            this.valueInfo=[1]
          }else{
            this.valueInfo=[]
          }
          this.model.isAutoConfirm=0
        }else{
          this.confirmDisabled=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(file) {
        if (this.fileList.length>=1) {
          this.$message.warning('只能上传一个文件')
          return false
        }
      },
      handleChange(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) {
                // file.url = this.urlDownload+file.response.message;
                this.model.serviceContract = 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(file)
        this.fileList = [];
      },
      getcontractType(val) {
        this.model.serviceContractType = val==''?null:val
      },
      //回显文件所用
      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
      },




      //上传文件2
      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
      },


      onChange(checkedValues){
        this.model.isAutoOrder=0
        this.model.isAutoConfirm=0
        if(checkedValues.length>0){
          for (let i = 0; i <checkedValues.length ; i++) {
             if(checkedValues[i]==1){
               this.model.isAutoOrder=1
             }
             if(checkedValues[i]==2){
               this.model.isAutoConfirm=1
             }
          }
        }
      }


    }
  }
</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;
  }

  .ant-upload{
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
  }
</style>