<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>
      <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">
                  <date-sigle ref="sigleRef" :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="returnCode">
                  <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" @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="refundReason">
          <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>
  </div>
</template>

<script>
import dateSigle from '@/components/dateSigle.vue'
import bUpload from '@/components/uploadFile.vue'
export default {
  props: {
    orderDetail: {},
    contractData: {},
    returnRes: {},
    returnInfo: {},
    isStatus: String,
    payMoney: Number
  },
  components: {
    dateSigle,
    bUpload
  },
  methods: {
    inited() {
      this.invoice.type = ''
      this.funds.sum = ''
      this.models.refundReason = ''
      this.contract.contractFileUrl = ''
      this.returned.returnVoucherUrl = ''
      this.returned.returnRemark = ''
      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
    },
    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: parseInt(this.returned.returnMoney?this.returned.returnMoney * 100:0),
        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) {
          return
        }
      })
      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()
        }
      })
    },
    backCancel() {
      this.backShow = false
      setTimeout(() => {
          this.inited()
      },500)
    },
    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: parseInt(this.funds.sum * 100),
          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)
    },
    subSave (name) {// 退款
      let sums = 0
      this.returnRes.forEach(v => {
        sums = sums + v.return_money
      })
      if (parseInt(this.models.refundMoney) > sums / 100) {
        this.$Message.warning('退款金额不能大于实收金额')
        return
      }
      let obj = {
        orderCode: this.orderDetail.order_code,
        refundMoney: parseInt(this.models.refundMoney * 100),
        refundReason: this.models.refundReason,
        isOffline: this.isStatus == 'qmx'? 1 : 0,
        refundStatus: this.payMoney == this.models.refundMoney ? 1 : 2
      }
      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.$parent.ordered()
              setTimeout(() => {
                this.isDisable = false
            },1000)
          }).error(() => {
              this.isDisable = false
          }).get()
        }
      })
    }
  },
  data() {
    return {
      iShow: false,
      backShow: false,
      pShow: false,
      sShow: false,
      tShow: false,
      isDisable: false,
      invoice: {
        type: ''
      },
      invoType:[
        {v: '1', n: '普通发票（纸质发票）'},
        {v: '2', n: '普通发票（电子发票）'},
        {v: '3', n: '专用发票（纸质发票）'}
      ],
      contract: {
        contractFileUrl: ''
      },
      funds: {
        sum: '',
        shCode: ''
      },
      models: {
        refundMoney: '',
        refundReason: ''
      },
      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: '已开具'}
      ],
      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' }
        ]
      }
    }
  }
}
</script>