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



        <a-form-item label="发布企业" :labelCol="labelCol" :wrapperCol="wrapperCol" v-has="'require:saas'" :required="true">
            <a-input-search
              placeholder="选择企业"
              disabled
              v-decorator="[ 'companyName', validatorRules.companyId]"
              @search="onSearch1">
              <a-button slot="enterButton" icon="search" v-if="!model.id">选择</a-button>
            </a-input-search>
        </a-form-item>


        <a-form-item label="需求名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="[ 'name', validatorRules.name]" placeholder="请输入需求名称" style="width: 100%"></a-input>
        </a-form-item>

        <a-form-item label="所属行业" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <j-dict-select-tag type="list" v-decorator="['tradeType',validatorRules.tradeType]" :trigger-change="true"
                             dictCode="trade_type" placeholder="请选择所属行业" style="width: 100%"/>
        </a-form-item>

        <a-form-item label="需求描述" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-textarea v-decorator="['description', validatorRules.description]" rows="4" placeholder="请输入需求描述" style="width: 100%"/>
        </a-form-item>

        <a-form-item label="接单资质" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-textarea v-decorator="['qualification', validatorRules.qualification]" rows="4" placeholder="请输入接单资质" style="width: 100%"/>
        </a-form-item>

        <a-form-item label="验收标准" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-textarea v-decorator="['acceptanceCriteria', validatorRules.acceptanceCriteria]" rows="4"
                      placeholder="请输入验收标准" style="width: 100%"/>
        </a-form-item>

        <a-form-item label="需求人数" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input-number :min="1" v-decorator="[ 'number']" placeholder="请输入需求人数, 不填表示若干" style="width: 100%"/>
        </a-form-item>


        <a-form-item label="结算方式" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <j-dict-select-tag type="list" @change="getselmethod"
                             v-decorator="['settlementMethod',validatorRules.settlementMethod]" :trigger-change="true"
                             dictCode="settlement_method" placeholder="请选择结算方式" style="width: 100%"/>
        </a-form-item>

        <template v-if="model.settlementMethod==1">
          <a-form-item label="期数" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input-number :min="1" v-decorator="[ 'stage', validatorRules.stage]" placeholder="请输入期数" style="width: 100%"/>
          </a-form-item>
        </template>

        <a-form-item label="参考单价" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input-number v-decorator="[ 'price', validatorRules.price]" placeholder="请输入参考单价" style="width: 100%"/>
        </a-form-item>

        <a-form-item label="服务期限" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-range-picker
            style="width: 100%"
            v-decorator="[ 'serviceTimeRange', validatorRules.serviceTimeRange]"
            format="YYYY-MM-DD"
            :placeholder="['开始时间', '结束时间']"
            @change="onDateChange"
            @ok="onDateOk"
            :allowClear="allowClear"
          />
        </a-form-item>

        <a-form-item label="工作地点" :labelCol="labelCol" :wrapperCol="wrapperCol" :required="true">
          <a-cascader :options="options" :value="arr" @change="onChange" placeholder="请选择工作地点"
                      changeOnSelect style="width: 100%"/>
        </a-form-item>

        <a-form-item label="详细地址" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="[ 'address', validatorRules.address]" placeholder="请输入详细地址" style="width: 100%"></a-input>
        </a-form-item>

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

        <!--<template v-if="model.contractType=='0'">-->
          <!--<a-form-item label="企业合同" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
            <!--<a-upload-->
              <!--name="file"-->
              <!--:multiple="true"-->
              <!--:action="uploadAction"-->
              <!--:headers="headers"-->
              <!--:data="{'isup':1,'bizPath':bizPath}"-->
              <!--:fileList="fileList"-->
              <!--:beforeUpload="beforeUpload"-->
              <!--@change="handleChange"-->
            <!--@preview="viewContract">-->
              <!--<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">-->
          <!--<a-input-number :min="0.01" :max="99.99" v-decorator="[ 'serviceFeeRate', validatorRules.serviceFeeRate]"-->
                          <!--:formatter="value => `${value}%`" :parser="value => value.replace('%', '')"-->
                          <!--placeholder="请输入服务费率"-->
                          <!--style="width: 100%"/>-->
        <!--</a-form-item>-->

        <a-form-item label="发布截止" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <j-date placeholder="请选择发布截止" v-decorator="[ 'expiryDate', validatorRules.expiryDate]" :trigger-change="true"
                  :show-time="true" date-format="YYYY-MM-DD" style="width: 100%"/>
        </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-select-window ref="companyWindow" @ok="modalFormOk1"></company-select-window>
  </a-modal>
</template>

<script>
  import { USER_AUTH,SYS_BUTTON_AUTH } from "@/store/mutation-types"
  import { httpAction,getAction } from '@/api/manage'
  import pick from 'lodash.pick'
  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 data1 from '../../tools/area.json'
  import Vue from 'vue'
  import { ACCESS_TOKEN } from '@/store/mutation-types'
  import moment from 'moment'
  import CompanySelectWindow from './CompanySelectWindow'

  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: 'HwRequirementModal',
    components: {
      CompanySelectWindow,
      JDate,
      JUpload,
      JSelectDepart,
      JDictSelectTag
    },
    data() {
      return {
        bodyStyle: {
          paddingTop: '20px',
          paddingBottom:'50px',
          height: (window.innerHeight * 0.68) + 'px',
          'overflow-y': 'auto'
        },
        allowClear:false,
        disableSubmit:false,
        uploadAction: window._CONFIG['domianURL'] + '/hpSys/common/ossUpload',
        urlDownload: window._CONFIG['domianURL'] + '/hpSys/common/ossDownload',
        headers: {},
        fileList: [],
        arr: [],  //存放回显默认省市区code
        provArray: [], //存放省
        cityArray: [],   //存放市
        countryArray: [],  //存放区
        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 }
        },
        options: [{
          value: '',
          label: '',
          isLeaf: false
        }],
        confirmLoading: false,
        selectedDepartKeys1:[], //保存用户选择企业id
        checkedDepartKeys1:[],
        companyId:0,
        validatorRules: {
          companyId:{ },
          platformCompanyId: { rules: [{ required: true, message: '请输入所属平台企业!' }] },
          code: { rules: [{ required: true, message: '请输入需求单号!' }] },
          name: { rules: [{ required: true, message: '请输入需求名称!' }] },
          tradeType: { rules: [{ required: true, message: '请输入所属行业' }] },
          description: { rules: [{ required: true, message: '请输入需求描述!' }] },
          qualification: { rules: [{ required: true, message: '请输入接单资质!' }] },
          acceptanceCriteria: { rules: [{ required: true, message: '请输入验收标准!' }] },
          number: { rules: [{ required: true, message: '请输入需求人数' }] },
          settlementMethod: { rules: [{ required: true, message: '请输入结算方式' }] },
          stage: { rules: [{ required: true, message: '请输入期数' }] },
          price: { rules: [{ required: true, message: '请输入参考单价' }] },
          address: {},
          serviceTimeRange:{rules: [{ required: true, message: '请选择服务期限范围' }] },
          serviceStartDate:{},
          serviceEndDate:{},
          serviceFeeRate: { rules: [{ required: true, message: '请输入服务费率!' }] },
          serviceContractType: { rules: [{ required: true, message: '请输入合同方式' }] },
          serviceContract: {},
          authenticationStatus: { rules: [{ required: true, message: '请输入认证状态' }] },
          expiryDate: { rules: [{ required: true, message: '请输入发布截止' }] },
          createTime: { rules: [{ required: true, message: '请输入发布时间' }] },
          isOn: { rules: [{ required: true, message: '请输入状态' }] },
          typeEdit:{},
        },
        url: {
          fileUpload: window._CONFIG['domianURL'] + '/hpSys/common/ossUpload',
          add: '/requiremanager/hwRequirement/add',
          edit: '/requiremanager/hwRequirement/edit',
          queryInfo:'/requiremanager/hwRequirement/queryInfo',
        }

      }
    },
    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: {
      value(val) {
        this.initFileList(val)
      }
    },
    created() {
      const token = Vue.ls.get(ACCESS_TOKEN)
      this.headers = { 'X-Access-Token': token }
      //省市区options完全拼接
      for (var i = 0; i < data1.length; i++) {
        this.cityArray = []
        for (let j = 0; j < data1[i].cityList.length; j++) {
          this.countryArray = []
          for (let k = 0; k < data1[i].cityList[j].areaList.length; k++) {
            var country = {
              value: data1[i].cityList[j].areaList[k].code,
              label: data1[i].cityList[j].areaList[k].name
            }
            this.countryArray.push(country)
          }
          var city = {
            value: data1[i].cityList[j].code,
            label: data1[i].cityList[j].name,
            children: this.countryArray
          }
          this.cityArray.push(city)
        }
        var prov = {
          value: data1[i].code,
          label: data1[i].name,
          children: this.cityArray
        }
        this.provArray.push(prov)
        this.options = this.provArray
      }

    },
    methods: {
      add() {
        this.edit({})
      },
      edit(record) {
        this.form = this.$form.createForm(this)
        this.form.resetFields()
        this.model = Object.assign({}, record)
        console.log( 111,this.model)
        this.visible = true
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, 'platformCompanyId','companyId', 'code', 'name',  'description', 'qualification', 'acceptanceCriteria', 'number', 'stage', 'price', 'provinceCode', 'cityCode', 'countryCode', 'provinceCityCountry', 'address', 'serviceContract', 'authenticationStatus', 'expiryDate', 'createTime', 'serviceFeeRate', 'isOn','typeEdit','companyAuthenticationStatus','serviceTimeRange','serviceStartDate','serviceEndDate'))
          this.form.setFieldsValue({ tradeType:this.model.tradeType!=null? String(this.model.tradeType):'' })
          this.form.setFieldsValue({ settlementMethod:this.model.settlementMethod!=null? String(this.model.settlementMethod):''})
          this.form.setFieldsValue({ serviceContractType:this.model.serviceContractType!=null?String(this.model.serviceContractType):''})
          this.form.setFieldsValue({ expiryDate:this.model.expiryDate?String(this.model.expiryDate).substring(0,10):null})
          this.model.expiryDate=String(this.model.expiryDate).substring(0,10)
          this.form.setFieldsValue({ serviceTimeRange:this.model.serviceStartDate!=null?[moment(this.model.serviceStartDate, 'YYYY/MM/DD'), moment(this.model.serviceEndDate, 'YYYY/MM/DD')]:[]})
          // console.log(this.model.serviceStartDate)
          // console.log( this.model.serviceEndDate)
          this.selectedDepartKeys1 = [];
          this.checkedDepartKeys1 = [];
          this.companyId=0

        })

        //回显省市区
        this.arr = []
        this.arr.push(String(this.model.provinceCode))
        this.arr.push(String(this.model.cityCode))
        this.arr.push(String(this.model.countryCode))
        console.log(111111, this.arr)

        //回显文件
        this.editFileList(this.model.serviceContract)


        //没有选择企业权限时componyid（部门id）掷为null
        //获取页面权限
        let authList = JSON.parse(sessionStorage.getItem(USER_AUTH) || "[]");
        var bo=false;
        for (var auth of authList) {
          if(auth.action == 'require:saas') {
                bo=true
          }
        }
        if(!bo){
          this.model.companyId=null
          this.form.setFieldsValue({ companyId:null})
        }
      },
      close() {
        this.$emit('close')
        this.visible = false
      },
      handleOk() {
        if(this.model.typeEdit==1){
          this.model.id=null
          this.model.serviceFeeRate=null
          this.model.subcontractorFeeRate=null
          this.model.serviceContractType=null
          this.model.serviceContract=null
          this.model.subcontractType=null
          this.model.subcontract=null
          this.model.workContractType=null
          this.model.authenticationStatus=0
        }
        // if(this.model.contractType ==0){
        //   if(!this.model.serviceContract || this.fileList.length==0){
        //     this.$message.warning('请上传企业合同')
        //     return
        //   }
        // }
        if (this.arr.length != 3 || this.arr[0] == 'undefined') {
          this.$message.warning('请选择工作地址')
          return
        }
        var companyName = this.form.getFieldValue('companyName');
        if(!companyName){
          //获取页面权限
          let authList = JSON.parse(sessionStorage.getItem(USER_AUTH) || "[]");
          for (var auth of authList) {
            if(auth.action == 'require:saas') {
              this.$message.warning('请选择企业')
              return;
            }
          }
        }
        console.log(11111111111, this.form.getFieldValue("expiryDate"))
        if(new Date(this.form.getFieldValue("expiryDate")+" 00:00:00").getTime()<new Date().getTime()){
          this.$message.warning('截止时间需大于今天')
          return
        }
        // if(!this.model.serviceStartDate || !this.model.serviceEndDate){
        //   this.$message.warning('请选择服务期限')
        //   return
        // }
        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)
            formData.expiryDate=this.model.expiryDate+" 23:59:59"
            if(this.selectedDepartKeys1[0]){
              formData.companyId=this.companyId
            }
            console.log('表单提交数据', formData)
            httpAction(httpurl, formData, method).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
                that.close()
              } else {
                this.$error({
                  title: '提示',
                  content: res.message,
                  okText: '确定',
                  centered:true,
                  onOk: () => {

                  }
                })
              }
            }).finally(() => {
              that.confirmLoading = false
            })
          }

        })
      },
      handleCancel() {
        this.close()
      },
      popupCallback(row) {
        this.form.setFieldsValue(pick(row, 'platformCompanyId','companyId', 'code', 'name', 'tradeType', 'description', 'qualification', 'acceptanceCriteria', 'number', 'settlementMethod', 'stage', 'price', 'provinceCode', 'cityCode', 'countryCode', 'provinceCityCountry', 'address', 'serviceContractType', 'serviceContract', 'authenticationStatus', 'expiryDate', 'createTime',  'serviceFeeRate','isOn','typeEdit','companyAuthenticationStatus','serviceTimeRange','serviceStartDate','serviceEndDate'))
      },

      //省市区改变
      onChange(value, label) {
        this.arr = value
        this.model.provinceCode = value[0]
        this.model.cityCode = value[1]
        this.model.countryCode = value[2]
        this.$nextTick(() => {
          this.form.setFieldsValue({ provinceCode: this.model.provinceCode })
          this.form.setFieldsValue({ cityCode: this.model.cityCode })
          this.form.setFieldsValue({ countryCode: this.model.countryCode })
          if (label.length == 3) {
            this.model.provinceCityCountry = label[0].label + '-' + label[1].label + '-' + label[2].label
            this.form.setFieldsValue({ provinceCityCountry: this.model.provinceCityCountry })
          }
        })

      },
      getselmethod(val) {
        this.model.settlementMethod = val
      },
      getcontractType(val) {
        this.model.serviceContractType = 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.urlDownload + '?fileName=' + arr[a],
          })
        }
        this.fileList = fileList
      },
      //上传文件所用
      initFileList(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.urlDownload + arr[a],
            response: {
              status: 'history',
              message: arr[a]
            }
          })
        }
        this.fileList = fileList
      },
      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(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 = [];
      },
      onDateChange: function (value, dateString) {
        console.log(dateString[0],dateString[1]);
        this.model.serviceStartDate=dateString[0]+" 00:00:00";
        this.model.serviceEndDate=dateString[1] +" 23:59:59";
      },
      onDateOk(value,dateString) {
        console.log(value);
      },
      viewContract(file){
        window.open(window._CONFIG['imgDomainOssURL']+this.model.serviceContract, '_blank', 'toolbar=yes')
      },

      //搜索企业
      onSearch1(){
        this.$refs.companyWindow.add(this.checkedDepartKeys1);
      },
      // 获取用户选择企业提交的返回数据
      modalFormOk1 (formData) {
        this.selectedDepartKeys1 = [];
        for (let i = 0; i < formData.departIdList.length; i++) {
          this.selectedDepartKeys1.push(formData.departIdList[i].key);
          this.form.setFieldsValue({ companyName: formData.departIdList[i].title })
        }
        this.checkedDepartKeys1 = this.selectedDepartKeys1  //更新当前的选择keys
        if(this.selectedDepartKeys1[0]){
          this.companyId = this.selectedDepartKeys1[0];
          getAction(this.url.queryInfo,{companyId:this.companyId}).then((res)=>{
            console.log(222,res.message)
            if(res.success){

            }else{
              this.$error({
                title: '提示',
                content: res.message,
                okText: '确定',
                centered:true,
                onOk: () => {
                    this.close()
                }
              })
            }
          });
        }
      },




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