<template>
  <a-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    :maskClosable="false"
    cancelText="关闭">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <span style="color: rgba(0, 0, 0, 0.85);font-size: 16px;font-weight: 600;">{{comTitle}}：<a style="font-size: 13px;margin-left: 10px;font-weight:400;"><a-icon type="info-circle" :style="{ fontSize: '14px' }" />{{comDescripetion_New}}</a></span>

        <a-form-item label="项目金额" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-top: 10px;margin-bottom: 18px;">
          {{model.payment}}
          <!--<a-input-number v-decorator="[ 'amount', validatorRules.amount]" placeholder="请输入项目金额" style="width: 100%"/>-->
        </a-form-item>
          
        <a-form-item label="服务费" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input-number v-decorator="[ 'serviceFee', validatorRules.serviceFee]" :precision="2" placeholder="请输入服务费" style="width: 100%" @change="serviceFeeChange"/>
        </a-form-item>

        <a-form-item label="入账时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-date-picker placeholder="请选择入账时间" v-decorator="[ 'businessTime', validatorRules.businessTime]"
                  style="width: 100%" :showTime="true" dateFormat="YYYY-MM-DD HH:mm:ss"/>
        </a-form-item>

        <template v-if="model.subcontractType != null">
          <span style="color: rgba(0, 0, 0, 0.85);font-size: 16px;font-weight: 600;">平台入账到服务商：<a style="font-size: 13px;margin-left: 10px;font-weight:400;"><a-icon type="info-circle" :style="{ fontSize: '14px' }" />{{comDescripetion_c_New}}</a></span>

          <a-form-item label="项目金额" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-top: 10px;margin-bottom: 18px;">
            {{model.payment}}
            <!--<a-input-number v-decorator="[ 'amount', validatorRules.amount]" placeholder="请输入项目金额" style="width: 100%"/>-->
          </a-form-item>

          <a-form-item label="外包服务费" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input-number v-decorator="[ 'subServiceFee', validatorRules.subServiceFee]" :precision="2" placeholder="请输入外包服务费" style="width: 100%" @change="subServiceFeeChange"/>
          </a-form-item>

          <a-form-item label="入账时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-date-picker placeholder="请选择入账时间" v-decorator="[ 'subBusinessTime', validatorRules.subBusinessTime]"
                    style="width: 100%" :showTime="true" dateFormat="YYYY-MM-DD HH:mm:ss"/>
          </a-form-item>
        </template>

      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>

  import { httpAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import JDate from '@/components/jeecg/JDate'
  import moment from "moment"
  
  export default {
    name: "HwPaymentDetailModal",
    components: { 
      JDate,
    },
    data () {
      return {
        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 },
        },
        comTitle:'企业入账到平台',
        comDescripetion:'请确认平台已到款',
        comDescripetion_New:'',
        comDescripetion_c:'请确认服务商已到款',
        comDescripetion_c_New:'',
        show:true,//动态显示隐藏表单元素
        routeSwitch:true, //是否通过平台
        isThroughPlatform:1,//是否通过平台（0：否 1：是）
        confirmLoading: false,
        validatorRules:{
          amount:{rules: [{ required: true, message: '请输入项目金额!' }]},
          serviceFee:{rules: [{ required: true, message: '请输入服务费!' }]},
          serialNumber:{rules: [{ required: true, message: '请输入流水号!' }]},
          subServiceFee:{rules: [{ required: true, message: '请输入外包服务费!' },
              {validator: this.validateSubServiceFee},{validator: this.validateSub}
              ]},
          subSerialNumber:{rules: [{ required: true, message: '请输入流水号!' }]},
          businessTime:{rules: [{ required: true, message: '请选择入账时间!' }]},
          subBusinessTime:{rules: [{ required: true, message: '请选择入账时间!' }]},
        },
        url: {
          add: "/saasmanager/hwPlatformCompanyAccountDetail/add",
        }
     
      }
    },
    created () {
    },
    methods: {
      moment,
      add () {
        this.edit({});
      },
      edit (record) {
        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.model.paymentId = this.model.id;
        this.model.id = null;
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'paymentId','subId','paymentCompanyId','requirementId','subcontractType','payment'));
          //入账时间默认当前时间
          this.form.setFieldsValue({businessTime: moment(new Date(), 'YYYY-MM-DD HH:mm:ss')}) //时间格式化
          this.form.setFieldsValue({subBusinessTime: moment(new Date(), 'YYYY-MM-DD HH:mm:ss')}) //时间格式化
        });
        if (record.subcontractType != null) {
          this.isThroughPlatform = 1;
          this.comTitle = '企业入账到平台';
          this.comDescripetion = '请确认平台已到款';
        } else {
          this.isThroughPlatform = 0;
          this.comTitle = '企业入账到服务商';
          this.comDescripetion = '请确认服务商已到款';
        }
        this.comDescripetion_New = this.comDescripetion;
        this.comDescripetion_c_New = this.comDescripetion_c;
      },
      close () {
        this.$emit('close');
        this.visible = false;
      },
      handleOk () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            httpurl+=this.url.add;
            method = 'post';
            let formData = Object.assign(this.model, values);
            formData.amount = this.model.payment;
            formData.isThroughPlatform = this.isThroughPlatform;
            //时间格式化
            formData.businessTime = formData.businessTime ? formData.businessTime.format('YYYY-MM-DD HH:mm:ss') : null;
            formData.subBusinessTime = formData.subBusinessTime ? formData.subBusinessTime.format('YYYY-MM-DD HH:mm:ss') : null;
            console.log("表单提交数据",formData)
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$error({
                  title: '错误提示',
                  content: res.message,
                  okText: '确定',
                  centered:true
                })
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })
          }
         
        })
      },
      handleCancel () {
        this.close()
      },
      popupCallback(row){
        this.form.setFieldsValue(pick(row,'paymentId','subId','paymentCompanyId','requirementId','subcontractType','payment'))
      },
      //验证外包服务费小于服务费
      validateSubServiceFee(rule, value, callback){
        if(!value){
          callback()
        }else{
          let serviceFee = this.form.getFieldValue('serviceFee')
          if(value < serviceFee){
            callback()
          }else{
            callback("外包服务费需小于服务费")
          }
        }
      },
      //校验正数字
      validateSub(rule, value, callback){
        if(!value){
          callback()
        }else{
          if(new RegExp(/^((0{1}\.\d{1,2})|([1-9]\d*\.{1}\d{1,2})|([1-9]+\d*)|0)$/).test(value)){
            callback()
          }else{
            callback("请输入正确的数字，最多俩位小数")
          }
        }
      },
      //服务费监听
      serviceFeeChange(value){
        var money;
        if(value){
          money = this.numAdd(this.model.payment,value)
        }else{
          money = this.numAdd(this.model.payment,0)
        }
        this.comDescripetion_New = this.comDescripetion + money + '元';
      },
      //外包服务费监听
      subServiceFeeChange(value){
        var money;
        if(value){
          money = this.numAdd(this.model.payment,value)
        }else{
          money = this.numAdd(this.model.payment,0)
        }
        this.comDescripetion_c_New = this.comDescripetion_c + money + '元';
      },
      /**
       * 加法运算，避免数据相加小数点后产生多位数和计算精度损失。
       * @param num1
       * @param num2
       * @returns {number}
       */
      numAdd(num1, num2) {
        var baseNum, baseNum1, baseNum2;
        try {
          baseNum1 = num1.toString().split(".")[1].length;
        } catch (e) {
          baseNum1 = 0;
        }
        try {
          baseNum2 = num2.toString().split(".")[1].length;
        } catch (e) {
          baseNum2 = 0;
        }
        baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
        return (num1 * baseNum + num2 * baseNum) / baseNum;
      }
      //监听switch选择
      // onChose(checked) {
      //   if (checked) {
      //     this.show = true;
      //     this.isThroughPlatform = 1;
      //     this.comTitle = '企业入账到平台';
      //   } else {
      //     this.show = false;
      //     this.isThroughPlatform = 0;
      //     this.comTitle = '企业入账到服务商';
      //   }
      // },
    }
  }
</script>
