<template>
  <div class="detail-model">
    <!-- 线下开发票 -->
    <Modal title="线下开发票" v-model="iShow" class-name="order-model piao-model" :mask-closable="false" @on-visible-change="visibleChange">
      <!-- <Select placeholder="请选择发票类型" v-model="invoice.type" style="width:100%;margin: 20px 0">
          <Option v-for="item in invoType" :value="item.n" :key="item.v">{{ item.n }}</Option>
      </Select> -->
      <p style="text-align:center;margin:16px 0;font-size:15px">确定线下开发票吗？如若确定，则会关闭用户线上开票入口。</p>
      <div slot="footer">
          <Button type="primary" size="large" @click="invoSave" :disabled="isDisable">确定</Button>
          <Button size="large" @click="iShow = false">取消</Button>
      </div>
    </Modal>
    <!-- 新增回款信息 -->
    <Modal title="新增回款信息" v-model="backShow" class-name="order-model back-model" :mask-closable="false" @on-visible-change="visibleChange1">
      <Form ref="backed" :model="backed" :rules="backRuleValidate" :label-width="110">
        <FormItem label="回款状态" prop="return_status">
            <Select v-model="backed.return_status" placeholder="请选择回款状态">
                <Option v-for="item in backSats" :value="item.v" :key="item.v">{{ item.n }}</Option>
            </Select>
        </FormItem>
        <FormItem label="回款交易详情" class="back-list">
          <Form ref="returned" :model="returned" :rules="backDetailValidate">
            <Row :gutter="10" class="back-row">
              <Col span="8">
                <FormItem prop="returnTime" v-if="visibleChange1">
                  <date-sigle ref="sigleRef" :dateType="'date'" :placeholderd="'请选择回款时间'" @startDate="startDate" :overTime="0"></date-sigle>
                </FormItem>
              </Col>
              <Col span="8">
                <FormItem prop="returnMoney">
                  <Input 
                      v-model="returned.returnMoney" 
                      type="text" 
                      placeholder="请输入回款金额" 
                      :maxlength="9"
                      @on-keyup="returned.returnMoney=inptReg(returned.returnMoney)"
                    ></Input>
                </FormItem>
              </Col>
              <Col span="8">
                <FormItem prop="">
                  <Input 
                    v-model="returned.returnRemark" 
                    type="text" 
                    placeholder="请输入回款说明(选填)" 
                  ></Input>
                </FormItem>
              </Col>
            </Row>
            <Row :gutter="10" class="back-row">
              <Col span="8">
                <FormItem prop="returnType">
                  <Select v-model="returned.returnType" placeholder="请选择支付方式">
                      <Option v-for="item in backPayType" :value="item.v" :key="item.v">{{ item.n }}</Option>
                  </Select>
                </FormItem>
              </Col>
              <Col span="8">
                <FormItem prop="">
                  <Input 
                    v-model="returned.returnCode" 
                    type="text" 
                    placeholder="请输入支付单号" 
                  ></Input>
                </FormItem>
              </Col>
              <Col span="8">
                <FormItem prop="returnInvoiceStatus">
                  <Select v-model="returned.returnInvoiceStatus" placeholder="请选择发票状态">
                      <Option v-for="item in backInvoStas" :value="item.v" :key="item.v">{{ item.n }}</Option>
                  </Select>
                </FormItem>
              </Col>
            </Row>
            <FormItem prop="">
              <b-upload 
                ref="uploadRef1"
                @fileData="fileData" 
                :placeholdered="'请上传凭证'"
                :accepted="'.jpg,.png,.jpeg'"
                :formated="['jpg','png','jpeg']"
                :multipled="false"
                :validateVar="returned.returnVoucherUrl"
              ></b-upload>
            </FormItem>
          </Form>
        </FormItem>
      </Form>
      <div slot="footer">
          <Button type="primary" size="large" @click="backSave" :disabled="isDisable">提交</Button>
          <Button size="large" @click="backCancel">取消</Button>
      </div>
    </Modal>
    <!-- 上传合同 -->
    <Modal title="上传合同" v-model="pShow" class-name="order-model contract-model" :mask-closable="false" @on-visible-change="visibleChange">
      <b-upload 
        ref="uploadRef2" 
        @fileData="contractFile" 
        :placeholdered="'请上传合同'" 
        :accepted="'.doc,.pdf,.docx,.rar,.zip,.jpg,.png,.jpeg'"
        :formated="['doc','pdf','docx','rar','zip','jpg','png','jpeg']"
        :multipled="false"
      ></b-upload>
      <div slot="footer">
          <Button type="primary" size="large" @click="pingSub" :disabled="isDisable">提交</Button>
          <Button size="large" @click="pingCancel">取消</Button>
      </div>
    </Modal>
    <!-- 审核 -->
    <Modal title="审核" v-model="sShow" class-name="shen-model" :mask-closable="false" @on-visible-change="visibleChange">
        <p>请确认此订单审核结果！</p>
        <Input type="tel" placeholder="请输入应付金额（元）" v-model="funds.sum" :maxlength="9" @on-keyup="funds.sum=inptReg(funds.sum)"></Input>
        <div slot="footer">
            <Button type="primary" size="large" @click="subConfirm">通过</Button>
            <Button type="error" size="large" @click="defeated">失败</Button>
            <Button size="large" @click="sShow = false">取消</Button>
        </div>
    </Modal>
    <!-- 退款登记 -->
    <Modal title="退款登记" v-model="tShow" class-name="order-model tui-model" :mask-closable="false" @on-visible-change="visibleChange">
      <Form ref="models" :model="models" :rules="refundRuleValidate" :label-width="110">
        <FormItem label="退款金额" prop="refundMoney">
            <Input v-model="models.refundMoney" type="text" :maxlength="9" placeholder="请输入退款金额" @on-keyup="models.refundMoney=inptReg(models.refundMoney)"></Input>
        </FormItem>
        <FormItem label="退款原因" prop="refundType">
          <Select placeholder="请选择退款原因" clearable v-model="models.refundType">
            <Option v-for="item in refundType" :value="item.v" :key="item.v">{{ item.n }}</Option>
          </Select>
        </FormItem>
        <FormItem label="备注">
          <Input v-model="models.refundReason" type="textarea" size="large" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入备注"></Input>
        </FormItem>
      </Form>
      <div slot="footer">
          <Button type="primary" size="large" @click="subSave('models')" :disabled="isDisable">提交</Button>
          <Button size="large" @click="tShow = false">取消</Button>
      </div>
    </Modal>
    <!-- 修正记录 -->
    <Modal title="红冲" v-model="correctionShow" class-name="order-model tui-model" :mask-closable="false" @on-visible-change="visibleChange">
      <!-- <label class="correctionLabel">请输入该订单最终准确的信息：</label> -->
      <Form ref="correctionModels" :model="models" :label-width="110">
        <FormItem label="红冲类型">
            <CheckboxGroup v-model="models.redType" @on-change="checkAllGroupChange">
                <Checkbox label="签约主体红冲"></Checkbox>
                <Checkbox label="金额红冲"></Checkbox>
            </CheckboxGroup>
        </FormItem>
        <p class="correctionLabel">请输入该订单最终准确的信息：</p>
        <FormItem label="签约主体" v-if="redCorrection == 3 || redCorrection == 1">
            <Input v-model="signingSubject" type="text" :maxlength="50" disabled placeholder="请输入签约主体"></Input>
        </FormItem>
        <FormItem label="大会员应付金额" v-if="(redCorrection == 3 || redCorrection == 2) && bigCorrection">
            <Input v-model="models.bigPayMoney" type="text" :maxlength="9" placeholder="请输入大会员应付金额"></Input>
        </FormItem>
        <FormItem label="子账号应付金额" v-if="(redCorrection == 3 || redCorrection == 2) && bigCorrection">
            <Input v-model="models.subMoney" type="text" :maxlength="9" :disabled="!(filterData.subPayMoney && filterData.subPayMoney>0)" placeholder="请输入子账号应付金额"></Input>
        </FormItem>
        <FormItem label="补充包应付金额" v-if="(redCorrection == 3 || redCorrection == 2) && bigCorrection">
            <Input v-model="models.supplyMoney" type="text" :maxlength="9" :disabled="!(filterData.supplyPayMoney && filterData.supplyPayMoney>0)" placeholder="请输入补充包应付金额"></Input>
        </FormItem>
        <FormItem label="订单金额" v-if="(redCorrection == 3 || redCorrection == 2) && !bigCorrection">
            <Input v-model="models.orderMoney" type="text" :maxlength="9" placeholder="请输入订单金额"></Input>
        </FormItem>
        <FormItem label="应付金额" v-if="(redCorrection == 3 || redCorrection == 2) && !bigCorrection">
            <Input v-model="models.payMoney" type="text" :maxlength="9" placeholder="请输入应付金额"></Input>
        </FormItem>
        <FormItem label="佣金" v-if="redCorrection == 3 || redCorrection == 2">
            <Input v-model="models.commission" type="text" :maxlength="9" placeholder="请输入佣金"></Input>
        </FormItem>
        <FormItem label="手续费" v-if="redCorrection == 3 || redCorrection == 2">
            <Input v-model="models.proceduresMoney" type="text" :maxlength="9" placeholder="请输入手续费"></Input>
        </FormItem>
        <FormItem label="修正原因">
          <Select placeholder="请选择修正原因" clearable v-model="models.correctionType">
            <Option v-for="item in correctionType" :value="item.v" :key="item.v">{{ item.n }}</Option>
          </Select>
        </FormItem>
        <FormItem label="">
          <Input v-model="models.correctionReason" v-if="models.correctionType === '其他'" type="textarea" size="large" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入修正原因"></Input>
        </FormItem>
      </Form>
      <div slot="footer">
          <Button type="primary" size="large" @click="correctionSave()" :disabled="redCorrection == 4">提交</Button>
          <Button size="large" @click="correctionShow = false">取消</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import dateSigle from '@/components/dateSigle.vue'
import bUpload from '@/components/uploadFile.vue'
export default {
  props: {
    orderDetail: {},
    contractData: {},
    returnRes: {},
    returnInfo: {},
    filterData: {},
    isStatus: String,
    payMoney: Number
  },
  components: {
    dateSigle,
    bUpload
  },
  methods: {
    inited() {
      this.invoice.type = ''
      this.funds.sum = ''
      this.models.refundReason = ''
      this.models.refundType = ''
      this.models.correctionReason = ''
      this.models.correctionType = ''
      this.contract.contractFileUrl = ''
      this.returned.returnVoucherUrl = ''
      this.returned.returnRemark = ''
      this.returned.returnCode = ''
      this.$refs.sigleRef.initd()
      this.$refs['backed'].resetFields()
      this.$refs['returned'].resetFields()
      this.$refs['models'].resetFields()
      this.$refs.uploadRef1.uploadShow = false
      this.$refs.uploadRef1.payHtml = ''
      this.$refs.uploadRef2.uploadShow = false
      this.$refs.uploadRef2.payHtml = ''
    },
    inptReg(val) {
      return val.match(/\d+(\.\d{0,2})?/) ? val.match(/\d+(\.\d{0,2})?/)[0] : ''
    },
    visibleChange1(val) {
      if (val == false) {
          setTimeout(() => {
              this.inited()
          },500)
      } else {
          this.isDisable = false
      }
    },
    visibleChange(val) {
      if (val == false) {
          setTimeout(() => {
              this.inited()
          },500)
      } else {
          this.isDisable = false
      }
    },
    invoSave() {// 线下开发票 
      // if (this.invoice.type == '') {
      //   this.$Message.warning('请选择发票类型')
      //   return
      // }
      this.isDisable = true
      this.$request('/order/openInvoice').data({
        orderCode: this.orderDetail.order_code,
        // invoiceType: this.invoice.type,
        // userId: this.orderDetail.user_id
      }).showSuccessTip().success(() => {
        this.$parent.ordered()
        this.iShow = false
        this.inited()
        setTimeout(() => {
          this.isDisable = false
        },1000)
      }).error(() => {
          this.isDisable = false
      }).post()
    },
    fileData(val) {
      this.returned.returnVoucherUrl = val
    },
    contractFile(val) {
      this.contract.contractFileUrl = val
    },
    startDate(val) {
      this.returned.returnTime = val
    },
    fixedNum(val) {
      return val ? Number(parseFloat(val * 100).toFixed(0)) : 0
    },
    backSave() {// 新增回款信息提交
      let obj = {
        id: parseInt(this.orderDetail.id),
        orderCode: this.orderDetail.order_code,
        return_status: parseInt(this.backed.return_status?this.backed.return_status:0),
        returnTime: this.returned.returnTime,
        returnMoney: this.fixedNum(this.returned.returnMoney),
        returnRemark: this.returned.returnRemark,
        returnType: parseInt(this.returned.returnType?this.returned.returnType:0),
        returnCode: this.returned.returnCode,
        returnInvoiceStatus: parseInt(this.returned.returnInvoiceStatus?this.returned.returnInvoiceStatus:0),
        returnVoucherUrl: this.returned.returnVoucherUrl
      }
      this.$refs.backed.validate((valid) => {
        if (valid) {
            this.$refs.returned.validate((valid) => {
                if (valid) {
                  this.isDisable = true
                  this.$request('/order/editReturnInfo').data(
                    obj
                  ).showSuccessTip().success(() => {
                    this.backShow = false
                    this.$parent.ordered()
                    this.inited()
                    setTimeout(() => {
                        this.isDisable = false
                    },1000)
                  }).error(() => {
                      this.isDisable = false
                  }).post()
                }
            })
        } else {
            this.$refs.returned.validate((valid) => {
                if (valid) {}
            })
        }
      })
      
    },
    backCancel() {
      this.backShow = false
    },
    pingSub() {// 上传合同
      if (!this.contract.contractFileUrl) {
        this.$Message.warning('请上传合同')
        return
      }
      this.isDisable = true
      this.$request('/order/uploadContractFile').data({
        contractId: $.isEmptyObject(this.contractData) == false?this.contractData.id:'',
        orderCode: this.orderDetail.order_code,
        contractFileUrl: this.contract.contractFileUrl
      }).showSuccessTip().success(() => {
        this.$parent.ordered()
        this.pShow = false
        this.inited()
        setTimeout(() => {
            this.isDisable = false
        },1000)
      }).error(() => {
          this.isDisable = false
      }).post()
    },
    pingCancel() {
      this.pShow = false
      setTimeout(() => {
          this.inited()
      },500)
    },
    audFunc(num) {
      this.isDisable = true
      this.$request('/order/orderList/transferAccounts').data({
          pay_money: this.fixedNum(this.funds.sum),
          order_code: this.orderDetail.order_code,
          courseStatus: num
      }).showSuccessTip().success(() => {
          this.$parent.ordered()
          this.sShow = false
          this.inited()
          setTimeout(() => {
            this.isDisable = false
        },1000)
      }).error(() => {
          this.isDisable = false
      }).post()
    },
    subConfirm() {// 订单审核通过
      if (this.funds.sum == '') {
          this.$Message.warning('应付金额为必填项')
          return
      }
      this.audFunc(4)
    },
    defeated() {// 订单审核失败
        this.audFunc(3)
    },
    qmxed() {
      if (this.isStatus == 'qmx') {
        return this.returnInfo.money == this.fixedNum(this.models.refundMoney) ? 1 : 2
      } else {
        return this.fixedNum(this.models.refundMoney) > this.payMoney || this.fixedNum(this.models.refundMoney) == this.payMoney ? 1 : 2
      }
    },
    subSave (name) {// 退款
      let sums = 0
      if (this.isStatus == 'qmx') {
        this.returnRes.forEach(v => {
          sums = sums + v.return_money
        })
        if (this.fixedNum(this.models.refundMoney) / 100 > sums / 100) {
          this.$Message.warning('退款金额不能大于已回款金额！')
          return
        }
      }
      let obj = {
        orderCode: this.orderDetail.order_code,
        refundMoney: this.fixedNum(this.models.refundMoney),
        refundReason: this.models.refundReason,
        refundType: this.models.refundType,
        isOffline: this.isStatus == 'qmx'? 1 : 0,
        refundStatus: this.qmxed()
      }
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.isDisable = true
          this.$request('/order/orderList/confirmRefund').data(
            obj
          ).showSuccessTip().success(() => {
              this.tShow = false
              this.models.refundReason = ''
              this.models.refundType = ''
              this.$parent.ordered()
              setTimeout(() => {
                this.isDisable = false
            },1000)
          }).error(() => {
              this.isDisable = false
          }).get()
        }
      })
    },
    correctionSave () {
      if (this.models.correctionType === '') {
          this.$Message.warning('修正原因为必填项')
          return
      }
      let obj = {
        orderCode: this.orderDetail.order_code,
        orderMoney: this.fixedNum(this.models.orderMoney),
        payMoney: this.orderDetail.product_type === '大会员' ? this.fixedNum(this.models.bigPayMoney) : this.fixedNum(this.models.payMoney),
        bigSubMoney: this.fixedNum(this.models.subMoney),
        supplyMoney: this.fixedNum(this.models.supplyMoney),
        commission: this.fixedNum(this.models.commission),
        proceduresMoney: this.fixedNum(this.models.proceduresMoney),
        correctionReason: this.models.correctionType !== '其他' ? this.models.correctionType : this.models.correctionReason,
        redType: this.models.redType.join(','),
        signingSubject: this.signingSubject,
      }
      this.$request('/order/addUpdateRecord').data(
        obj
      ).showSuccessTip().success(() => {
        this.correctionShow = false
        this.$parent.ordered()
        this.inited()
      }).error(() => {}).get()
    },
    checkAllGroupChange (data) {
      if (data.length === 1 && data[0] === '签约主体红冲') {
        this.redCorrection = 1
      } else if (data.length === 1 && data[0] === '金额红冲') {
        this.redCorrection = 2
      } else if (data.length === 0) {
        this.redCorrection = 4
      } else {
        this.redCorrection = 3
      }
    }
  },
  data() {
    return {
      iShow: false,
      backShow: false,
      pShow: false,
      sShow: false,
      tShow: false,
      correctionShow: false,
      bigCorrection: false,
      redCorrection: 1,
      isDisable: false,
      invoice: {
        type: ''
      },
      invoType:[
        {v: '1', n: '普通发票（纸质发票）'},
        {v: '2', n: '普通发票（电子发票）'},
        {v: '3', n: '专用发票（纸质发票）'}
      ],
      contract: {
        contractFileUrl: ''
      },
      funds: {
        sum: '',
        shCode: ''
      },
      models: {
        refundMoney: '',
        refundReason: '',
        refundType: '',
        correctionType: '',
        correctionReason: '',
        bigPayMoney: '',
        subMoney: '',
        supplyMoney: '',
        orderMoney: '',
        payMoney: '',
        commission: '',
        proceduresMoney: '',
        redType: ['签约主体红冲']
      },
      backed: {
        return_status: ''
      },
      returned: {
        returnTime: '',
        returnRemark: '',
        returnCode: '',
        returnInvoiceStatus: '',
        returnMoney: '',
        returnType: '',
        returnVoucherUrl: ''
      },
      backSats: [
        // {v: '0', n: '未回款'},
        {v: '1', n: '全额回款'},
        {v: '2', n: '部分回款'}
      ],
      backPayType: [
        {v: '1', n: '微信'},
        {v: '2', n: '支付宝'},
        {v: '3', n: '对公转账'}
      ],
      backInvoStas: [
        {v: '0', n: '未申请'},
        {v: '1', n: '已申请'},
        {v: '2', n: '已开具'}
      ],
      refundType: [
        {v: '个人垫付退款', n: '个人垫付退款'},
        {v: '产品购买错误', n: '产品购买错误'},
        {v: '客户不满意', n: '客户不满意'},
        {v: '活动免单', n: '活动免单'},
        {v: '测试', n: '测试'},
        {v: '其他', n: '其他'}
      ],
      correctionType: [
        {v: '录入错误', n: '录入错误'},
        {v: '客户不再支付', n: '客户不再支付'},
        {v: '其他', n: '其他'}
      ],
      backRuleValidate: {
        return_status: [
          { required: true, message: '请选择回款状态', trigger: 'change' }
        ]
      },
      backDetailValidate: {
        returnTime: [
          { required: true, message: '请选择回款时间', trigger: 'change' }
        ],
        returnMoney: [
          { required: true, message: '请输入回款金额', trigger: 'change' }
        ],
        returnType: [
          { required: true, message: '请选择支付方式', trigger: 'change' }
        ],
        returnCode: [
          { required: true, message: '请输入支付单号', trigger: 'change' }
        ],
        returnInvoiceStatus: [
          { required: true, message: '请选择发票状态', trigger: 'change' }
        ],
        returnVoucherUrl: [
          { required: true, message: '请上传凭证', trigger: 'change' }
        ]
      },
      refundRuleValidate: {
        refundMoney: [
          { required: true, message: '退款金额不能为空', trigger: 'change' }
        ],
        refundType: [
          { required: true, message: '退款原因不能为空', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    signingSubject () {
      return this.orderDetail.signing_subject==='h01'?'北京拓普丰联信息科技股份有限公司':'北京剑鱼信息技术有限公司'
    }
  }
}
</script>
<style lang="scss">
.correctionLabel {
  font-size: 16px;
  font-weight: bold;
  color: red;
  margin-bottom: 10px;
}
</style>
