<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-card :bordered='false'>
        <a-form :form='form'>

          <a-form-item label='请选择业务模式'>
            <a-radio-group @change='changeIsThroughPlatform'
                           v-decorator="['isThroughPlatform',{rules: [{ required: true, message: '请选择业务模式!'}],initialValue:this.initialIsThroughPlatformValue}]">
                          <template v-if="isThroughPlatform.indexOf('1')!= -1">
              <a-radio value='1'>企业-接包商-服务商-用户</a-radio>
                          </template>
                          <template v-if="isThroughPlatform.indexOf('0')!= -1">
              <a-radio value='0'>企业-服务商-用户</a-radio>
                          </template>
            </a-radio-group>
          </a-form-item>

          <template v-if="isSwitch=='1'">
            <a-form-item label='请选择平台'>
              <a-radio-group @change='changePlatform'
                             v-decorator="['cpId',{rules: [{ required: true, message: '请选择平台!'}],initialValue:this.initialCpIdValue}]">
                <a-radio v-for='(item, key) in hlwCpSettingList' :key='key' :value='item.id'>{{ item.cpName }}</a-radio>
              </a-radio-group>
            </a-form-item>
          </template>


          <template v-if="isSwitch=='0'">
            <a-form-item label='请选择服务商'>
              <a-radio-group @change='changeSubcontractor'
                             v-decorator="['subcontractorId',{rules: [{ required: true, message: '请选择服务商!'}],initialValue:this.initiaSubcontractorIdValue}]">
                <a-radio v-for='(item, key) in subcontractorList' :key='key' :value='item.id'>{{ item.name }}</a-radio>
              </a-radio-group>
            </a-form-item>
          </template>

          <a-form-item :label=serviceRateName>
            <a-input-number :min='0.01' :max='99.99'
                            v-decorator="[ 'serviceRate', {rules: [{ required: true, message: '请输入“企业→平台”的服务费率!' }]}]"
                            :formatter='value => `${value}%`' :parser="value => value.replace('%', '')" :precision='2'
                            placeholder='请输入服务费率'
                            style='width: 100%' />
          </a-form-item>

          <template v-if="isSwitch=='1'">
            <a-form-item label='请选择服务商'>
              <a-radio-group @change='changCpSubcontractor'
                             v-decorator="['cpSubcontractorId',{rules: [{ required: true, message: '请选择服务商!'}],initialValue:this.initiaCpSubcontractorIdValue}]">
                <a-radio v-for='(item, key) in cpSubcontractorList' :key='key' :value='item.id'>{{ item.name }}
                </a-radio>
              </a-radio-group>
            </a-form-item>
          </template>


        </a-form>
      </a-card>
    </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>
  </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 findList = (params) => putAction('/saasmanager/hwPlatformCompany/applicationSubcontractorList', 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: 'HwCompanySubcontractorModal ',
  components: {
    CompanySubcontractorWindow

  },
  data() {
    return {
      serviceRateName:"请输入平台服务费率",
      subcontractorList: [],
      hlwCpSettingList: [],
      cpSubcontractorList: [],
      headers: {},
      fileList: [],
      form: this.$form.createForm(this),
      title: '操作',
      width: 800,
      bodyStyle: {
        paddingTop: '20px',
        paddingBottom: '50px',
        height: (window.innerHeight * 0.62) + '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,
      platformId: 0,
      companyId: 0,
      initialIsThroughPlatformValue: '1',
      initialCpIdValue: 1,
      initiaSubcontractorIdValue: 1,
      initiaCpSubcontractorIdValue: 1,
      isThroughPlatform: '1',
      isSwitch: '1',
      validatorRules: {},
      url: {
        add: '/saasmanager/hwPlatformCompany/companySubcontractorAdd',
        edit: '/saasmanager/hwPlatformCompany/companySubcontractoredit',
        fileUpload: window._CONFIG['domianURL'] + '/hpSys/common/ossUpload',
        imgerver: window._CONFIG['imgDomainOssURL']
        // queryBankInfo: "/hlgsubcontractor/hlgSubcontractorBankInformation/queryBankInfo",
      }

    }
  },
  props: {
    fileType: {
      type: String,
      required: false,
      default: FILE_TYPE_ALL
    },
    /*这个属性用于控制文件上传的业务路径*/
    bizPath: {
      type: String,
      required: false,
      default: '/hlgjob/hlgSubContract'
    }
  },
  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.resetFields()
      //清空数据初始化数据
      this.model = {}
      this.hlwCpSettingList = []
      this.subcontractorList = []
      this.cpSubcontractorList = []
      this.initialIsThroughPlatformValue = '1'
      this.initialCpIdValue = 1
      this.initiaSubcontractorIdValue = 1
      this.initiaCpSubcontractorIdValue = 1
      this.isThroughPlatform = '1'
      this.isSwitch = '1'
      this.model = Object.assign({}, record)
      this.companyId = this.model.companyId
      this.platformId = this.model.platformId
      this.querySubcontratorList()
      this.visible = true
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleOk() {
      const that = this
      const { fileList } = that
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          if (!this.form.getFieldValue('serviceRate')) {
            this.$message.error('请输入服务费率!')
          }
          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)
          formData.companyId = this.companyId
          if (formData.isThroughPlatform == '1') {
            delete formData.subcontractorId
          } else if (formData.isThroughPlatform == '0') {
            delete formData.cpSubcontractorId
            delete formData.cpId
          }
          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()
          })
        }

      })
    },
    close() {
      this.visible = false
    },
    handleCancel() {
      this.close()
    },
    changeIsThroughPlatform(e) {
      this.model.isThroughPlatform = e.target.value
      this.isSwitch = e.target.value
      if(this.isSwitch=='1'){
        this.serviceRateName="请输入平台服务费率"
      }else{
        this.serviceRateName="请输入服务商服务费率"
      }
    },
    changePlatform(e) {
      this.model.cpId = e.target.value
    },
    changeSubcontractor(e) {
      this.model.subcontractorId = e.target.value
    },
    changCpSubcontractor(e) {
      this.model.cpSubcontractorId = e.target.value
    },
    //查询所有服务商列表
    querySubcontratorList() {
      findList({ companyId: this.companyId }).then((res) => {
        if (res.success) {
          this.isThroughPlatform = res.result.isThroughPlatform
          this.initialIsThroughPlatformValue = res.result.isThroughPlatform.length == 1 ? res.result.isThroughPlatform : '1'
          this.model.isThroughPlatform = this.initialIsThroughPlatformValue
          this.isSwitch = this.initialIsThroughPlatformValue
          if(this.isSwitch=='1'){
            this.serviceRateName="请输入平台服务费率"
          }else{
            this.serviceRateName="请输入服务商服务费率"
          }
          //通过平台
          if (this.isThroughPlatform.indexOf('1') != -1) {
            this.hlwCpSettingList = res.result.hlwCpSettingList
            this.initialCpIdValue = res.result.hlwCpSettingList[0].id
            this.cpSubcontractorList = res.result.cpSubcontractorList
            this.initiaCpSubcontractorIdValue = res.result.cpSubcontractorList[0].id
            if (this.model.isThroughPlatform == '1') {
              this.model.cpId = res.result.hlwCpSettingList[0].id
              this.model.cpSubcontractorId = res.result.cpSubcontractorList[0].id
              this.$nextTick(() => {
                this.form.setFieldsValue({ serviceRate: res.result.serviceRate })
              })
            }
          }
          if (this.isThroughPlatform.indexOf('0') != -1) {
            this.subcontractorList = res.result.subcontractorList
            this.initiaSubcontractorIdValue = res.result.subcontractorList[0].id
            if (this.model.isThroughPlatform == '0') {
              this.model.subcontractorId = res.result.subcontractorList[0].id
            }
          }
        }
      })
    }


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