<template>
  <a-modal
    :title="title"
    :width="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">
          <template v-if="!model.id">
            <a-input-search
              placeholder="选择服务商"
              disabled
              v-decorator="[ 'subcontractorName', validatorRules.subcontractorId]"
              @search="onSearch">
              <a-button slot="enterButton" icon="search" v-if="!model.id">选择</a-button>
            </a-input-search>
          </template>
          <template v-else>
            <a-input v-decorator="[ 'subcontractorName', validatorRules.subcontractorId]"  :disabled="true"></a-input>
          </template>
        </a-form-item>

        <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('%', '')"
                          placeholder="请输入服务费率"
                          style="width: 100%"/>
        </a-form-item>

        <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>


      </a-form>
    </a-spin>
    <div class="drawer-bootom-button" v-show="!disableSubmit">
      <a-button class="ant-btn"  @click="handleCancel">取消</a-button>
      <a-button class="ant-btn ant-btn-primary" style="margin-left: 8px"  @click="handleOk">确定</a-button>
    </div>
    <company-subcontractor-window ref="companyWindow" @ok="modalFormOk"></company-subcontractor-window>
  </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 CompanySubcontractorWindow from './CompanySubcontractorWindow'

  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: "HlgCompanySubcontractorModal ",
    components: {
      CompanySubcontractorWindow
    },
    data () {
      return {
        accept:'.pdf',
        uploadAction: window._CONFIG['domianURL'] + '/hpSys/common/ossUpload',
        urlDownload: window._CONFIG['domianURL'] + '/hpSys/common/ossDownload',
        headers: {},
        fileList: [],
        form: this.$form.createForm(this),
        title:"操作",
        width:800,
        bodyStyle: {
          paddingTop: '50px',
          paddingBottom:'50px',
          height: (window.innerHeight * 0.30) + '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,
        companyId: 0,
        validatorRules:{
          subcontractorId:{rules: [{ required: true, message: '请输入服务商!' }]},
          serviceRate:{rules: [{ required: true, message: '请输入服务费率!' }]},
          serviceContract:{}
        },
        url: {
          add: "/hlgcompany/hlgCompanySubcontractor/add",
          edit: "/hlgcompany/hlgCompanySubcontractor/edit",
        }
     
      }
    },
    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 (companyId) {
        this.edit(companyId);
      },
      edit (companyId) {
        this.form.resetFields();
        this.companyId = companyId;
        this.visible = true;
        this.selectedDepartKeys = [];
        this.checkedDepartKeys = [];
      },
      close () {
        this.$emit('close');
        this.visible = false;
        this.selectedDepartKeys = [];
        this.checkedDepartKeys = [];
      },
      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);
            if(this.selectedDepartKeys[0]){
              formData.subcontractorId = this.selectedDepartKeys[0];
            }
            formData.companyId = this.companyId;
            console.log("表单提交数据",formData)
            console.log(httpurl)
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                console.log(11111111111)
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                console.log(111111133331111)
                that.$message.warning(res.message);
              }
            }).finally(() => {
              console.log(22222)
              that.confirmLoading = false;
              that.close();
            })
          }
         
        })
      },
      //搜索服务商
      onSearch(){
        this.$refs.companyWindow.add(this.checkedDepartKeys);
      },
      handleCancel () {
        this.close()
      },
      // 获取用户选择服务商弹提交的返回数据
      modalFormOk (formData) {
        this.selectedDepartKeys = [];
        for (let i = 0; i < formData.departIdList.length; i++) {
          this.selectedDepartKeys.push(formData.departIdList[i].key);
          this.form.setFieldsValue({ subcontractorName: formData.departIdList[i].title })
        }
        this.checkedDepartKeys = this.selectedDepartKeys  //更新当前的选择keys
      },



      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 = [];
      },

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