<template>
  <div class="detail-model new-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">
      <Form :label-width="110">
        <FormItem required label="归档时间">
          <date-sigle ref="sigleRef5" :dateType="'date'" :placeholderd="'请选择归档时间'" @startDate="guiDate"
                      :overTime="0"></date-sigle>
        </FormItem>
        <FormItem required label="归档份数">
          <Input v-model.number="contract.contract_archive_num" type="tel" maxlength="4" @on-keyup="payHandler"
                 placeholder="请输入归档份数"></Input>
        </FormItem>
        <FormItem  required label="归档协议">
          <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>
        </FormItem>
      </Form>

      <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="请输入备注" :maxlength="255"></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="红冲类型">
          <RadioGroup v-model="models.redType" @on-change="checkAllGroupChange">
            <Radio label="签约主体红冲"></Radio>
            <Radio label="金额红冲"></Radio>
          </RadioGroup>
        </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>
        <!-- bigPayMoney -->
        <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) && 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" :loading="btnloading">提交</Button>
        <Button size="large" @click="correctionShow = false">取消</Button>
      </div>
    </Modal>
    <!-- 权限开通 -->
    <Modal title="权限开通" v-model="permissionActivationShow" class-name="order-model permissionActivation-model"
      :mask-closable="false" @on-visible-change="permissionActivationVisible">
      <Form ref="permissionActivation" :model="permissionActivation" :label-width="120">
        <FormItem label="开通权益手机号" style="width: 460px;" required>
          <Input class="ipt-inpt" v-model="permissionActivation.phone" type="text" @on-keyup="keyHandler"
            :maxlength="11" placeholder="请输入手机号"></Input>
        </FormItem>
        <FormItem label="开始日期" style="width: 460px;" required>
          <date-sigle ref="sigleRef1" :dateType="'date'" :placeholderd="'请选择开始日期'" @startDate="startDate_"
            :overTime="0"></date-sigle>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="primary" size="large" @click="pa_Save" :disabled="pa_dis">确定</Button>
        <Button size="large" @click="permissionActivationShow = false">取消</Button>
      </div>
    </Modal>
    <!-- 权限开通 -->
    <Modal title="业绩变更" v-model="performanceShow" class-name="order-model performance-model" :mask-closable="false"
      @on-visible-change="performanceVisible">
      <Form ref="performance" :model="performanceFrom" :label-width="120">
        <FormItem label="请输入变更后业绩归属情况" class="formTitle" :label-width="230"></FormItem>
        <FormItem label="销售人员">
          <sale-select ref="saleRef" :saleType="'1'" @salePerson="salePerson" transfer></sale-select>
        </FormItem>
        <FormItem class="table-order1" v-show="saleTableData.length > 0">
          <Table border :columns="saleTable" :data="saleTableData">
            <template slot-scope="{ row }" slot="name">
              <strong>{{ row.name }}</strong>
            </template>
            <template slot-scope="{ row }" slot="saler_dept">
              <strong>{{ row.saler_dept }}</strong>
            </template>
            <template slot-scope="{ row, index }" slot="money">
              <Input style="padding: 0 10px;" v-model="saleTableData[index].money" type="number" placeholder="请输入"></Input>
            </template>
            <template slot-scope="{ row }" slot="channel">
              <span style="display:none;">{{ row.channel }}</span>
              <!-- <Input v-model="saleTableData[index].channel" type="number" placeholder="请输入"></Input> -->
              <Cascader :data="channelListGetters" v-model="row.channel" @on-change="(value,selectedData)=>{ onChangeCascader(value,selectedData,row)}" transfer />
              <!-- <v-cascader ref="casRef" :data-id="row.channel" :initVal="row.channel" placeholderType="销售渠道" type="1" quType="1" transfer></v-cascader> -->
            </template>
          </Table>
        </FormItem>
        <FormItem label="变更原因">
          <RadioGroup v-model="performanceFrom.changeReason">
            <Radio :label="item" v-for="item in reasonList" :key="item">{{item}}</Radio>
          </RadioGroup>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="primary" size="large" :disabled="performanceDis" @click="performanceSave">确定</Button>
        <Button size="large" @click="performanceShow = false">取消</Button>
      </div>
    </Modal>
    <!-- 微信/支付宝付款码 -->
    <Modal title="微信/支付宝付款码" v-model="paymentCodeShow" class-name="order-model payment-code-model" :mask-closable="false"
      @on-visible-change="onPaymentVisibleChange">
      <Form ref="performance" :model="paymentForm" :label-width="180">
        <FormItem label="付款金额（元）：">
          <Input v-model="paymentForm.money" type="number" placeholder="请输入付款金额" @on-change="onChangePayMoney"></Input>
        </FormItem>
        <FormItem label="付款方式：">
          <RadioGroup v-model="paymentForm.mode" @on-change="onChangePayWay">
            <Radio label="1">微信</Radio>
            <Radio label="2">支付宝</Radio>
          </RadioGroup>
        </FormItem>
        <div class="screenshot-container" ref="screenshotRef" v-loading="paymentLoading" element-loading-background="rgba(255,255, 255)">
          <img class="screenshot-logo" src="@/assets/images/logo_main.png" alt="logo">
          <div class="screenshot-content">
            <div class="screenshot-info">
              <p v-if="paymentForm.account">{{paymentForm.account}}</p>
              <p v-if="paymentForm.product">产品类型：{{paymentForm.product}}</p>
            </div>
            <div class="screenshot-money">金额 <i class="num">￥{{formatPrice(paymentForm.money, -1, true)}}</i></div>
            <div class="screenshot-code">
              <img :src="paymentForm.imgCode">
            </div>
            <p class="screenshot-tip">使用手机{{paymentForm.mode === '1' ? '微信' : '支付宝'}}扫描二维码支付</p>
            <p class="screenshot-date">此二维码有效期截至到：{{ dateFormatter(paymentForm.expire * 1000, 'yyyy年MM月dd日') || '--'}}</p>
          </div>
        </div>
      </Form>
      <div slot="footer" style="display:flex;flex-direction: column;align-items: center;">
        <Button style="width:100%;" type="primary" size="large" :disabled="saveCodeDisabled" @click="onSavePaymentCode">保存二维码</Button>
        <p class="guide-tip">将二维码发送给客户，引导客户扫码支付</p>
      </div>
    </Modal>
  </div>
</template>

<script>
import html2canvas from 'html2canvas'
import { mapGetters } from 'vuex'
import dateSigle from '@/components/dateSigle.vue'
import bUpload from '@/components/uploadFile.vue'
import saleSelect from '@/views/order/components/salesSelect.vue'
import { dateFormatter } from '@/assets/js/date'
import { copyImage } from '@/utils/copy'
// import { Loading } from 'element-ui';
import vCascader from '@/components/cascader'
import { getChannelCode, formatPrice, debounce } from '@/utils/globalFun'
import QRCode from 'qrcode'
import { ajaxGetPayCode } from '@/api/modules'
export default {
  name: 'newDetailModel',
  props: {
    data: {},
    orderDetail: {},
    contractData: {},
    returnRes: {},
    returnInfo: {},
    filterData: {},
    isStatus: String,
    payMoney: Number
  },
  components: {
    dateSigle,
    bUpload,
    saleSelect,
    vCascader
  },
  methods: {
    dateFormatter, formatPrice,
    inited() {
      this.invoice.type = ''
      this.funds.sum = ''
      this.redCorrection = 4
      this.models.redType = ""
      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] : ''
    },
    keyHandler() {
      this.permissionActivation.phone = this.permissionActivation.phone.replace(/[^\d]/g, '')
    },
    timeReg(val) {
      return new Date(dateFormatter(val, 'yyyy-MM-dd') + ' 00:00:00').getTime() / 1000
    },
    startDate_(val) {
      if (val) {
        this.permissionActivation.startTime = this.timeReg(val)
      } else {
        this.permissionActivation.startTime = ''
      }
    },
    permissionActivationVisible(val) {
      if (val) {
        this.permissionActivation.phone = this.orderDetail.user_phone || ''
        this.permissionActivation.orderCode = this.orderDetail.order_code
      } else {
        this.permissionActivation.phone = ''
        this.permissionActivation.startTime = ''
        this.permissionActivation.orderCode = ''
        this.$refs.sigleRef1.dataVals = ''
      }
    },
    pa_Save() {
      if (this.permissionActivation.phone == '') {
        this.$Notice.warning({ title: '请输入手机号' })
        return
      }
      if (this.permissionActivation.phone && !/^1[3456789]\d{9}$/.test(this.permissionActivation.phone)) {
        this.$Notice.warning({ title: '手机号格式不正确' })
        return
      }
      if (this.permissionActivation.startTime == '') {
        this.$Notice.warning({ title: '请选择开始日期' })
        return
      }
      this.pa_dis = true
      let obj = this.permissionActivation
      this.$request('/order/serviceOpen').data(obj).success(() => {
        this.$parent.ordered()
        this.permissionActivationShow = false
        this.$Message.success({ content: '提交成功' })
        this.pa_dis = false
      }).error(() => {
        this.pa_dis = false
      }).post()
    },
    performanceVisible(val) {
      if (val) {
        const { saleDataRes } = JSON.parse(JSON.stringify(this.data))
        let list =[]
        if (saleDataRes.saleFinal) {
          list = saleDataRes.saleFinal.list || []
          let sarr = list.map(ele => {
            return ele.id + ''
          })
          this.$nextTick(()=>{
            this.$refs.saleRef.salePerson = sarr
            setTimeout(() => {
            if (saleDataRes.saleFinal  && saleDataRes.saleFinal.list.length > 0) {
            let salelist = JSON.parse(JSON.stringify(saleDataRes.saleFinal.list))
            salelist.forEach(ele => {
              ele.channel = getChannelCode(this.channelListGetters, ele.distribution_channel)
              ele.money = ele.money / 100
            })
            this.saleTableData = salelist
            let ajaxinitSalelist = JSON.parse(JSON.stringify(saleDataRes.saleFinal.list))
             ajaxinitSalelist.forEach(ele => {
             ele.money = ele.money / 100
            //  ele.channel = ele.distribution_channel
            })
            this.ajaxinitSalelist = ajaxinitSalelist
          }  
          }, 500)
          })
           this.reasonList = saleDataRes.reason
        }
      }else{
        this.performanceFrom.changeReason = ''
        this.saleTableData = []
        this.$refs.saleRef.salePerson = []
      }
    },
      performanceSave() {
        let salesMoneylist = this.saleTableData.map(ele => {
          const channel = ele.channel[1]? ele.channel[1] : ''
          return { id: Number(ele.id), money: this.fixedNum(ele.money), channel: channel }
        })
        this.performanceDis = true
        this.$request('/order/saleRecord').data({
          orderCode: this.orderDetail.order_code,
          doType: "update",
          salesMoney: JSON.stringify(salesMoneylist),
          reason: this.performanceFrom.changeReason
       }).success((res) => {
            this.performanceDis = false
            this.$parent.ordered()
            if (res.data == 'success') {
              this.$Notice.success({ title: '提交成功' })
              this.performanceShow = false
            }
          }).error(() => {
            this.performanceDis = false
          }).post()

      },
      onChangeCascader(val, valList, row) {
        let list = this.saleTableData
        // console.log(JSON.stringify(row));
        list.forEach(v => {
          if (v.id === row.id) {
            v.distribution_channel = val[1]
            v.channel = val
          }
        })
      },
      salePerson(val){
        let saleNameArr = []
        let initlist = JSON.parse(JSON.stringify(this.ajaxinitSalelist))
        const channelMap = this.channelMapGetters
        val.forEach((v,i) => {
          let vjson = JSON.parse(v)
          saleNameArr.push({ name: vjson.username,id: vjson.id,saler_dept: vjson.deptName,money: '',channel: getChannelCode(this.channelListGetters, channelMap[vjson.deptId])})
          initlist.forEach((ele) =>{ 
            if(ele.id == vjson.id){
              saleNameArr[i].money = ele.money
              saleNameArr[i].channel = ele.channel ? ele.channel : getChannelCode(this.channelListGetters, channelMap[vjson.deptId])
            }
          })
        })
        this.saleTableData = saleNameArr
      },
      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
      },
      guiDate(val) {
        this.contract.contract_archive_time = val
      },
      payHandler() {
        this.contract.contract_archive_num = Number(String(this.contract.contract_archive_num).replace(/[^\d]+/g, ''))
      },
      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.$notify.warning({ title: '请上传归档协议'})
          return
        }
        this.isDisable = true
        this.$jyRequest('/jyOrderManager/order/uploadContractFile').data({
          contractId: $.isEmptyObject(this.contractData) == false ? this.contractData.id : -1,
          orderCode: this.orderDetail.order_code,
          contractFileUrl: this.contract.contractFileUrl,
          contract_archive_time: this.contract.contract_archive_time,
          contract_archive_num: this.contract.contract_archive_num,
        }).showSuccessTip().success(() => {
          this.pShow = false
          this.inited()
          setTimeout(() => {
            this.isDisable = false
          }, 1000)
          this.$emit('refresh', '协议信息')
        }).error(() => {
          this.isDisable = false
        }).post()
      },
      pingCancel() {
        this.pShow = false
        setTimeout(() => {
          this.inited()
        }, 500)
      },
      audFunc(num) {
        this.isDisable = true
        this.$jyRequest('/jyOrderManager/order/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),
          payMoney: 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,
          signingSubject: this.signingSubject,
        }
        this.btnloading = true
        this.$request('/order/addUpdateRecord').data(
          obj
        ).showSuccessTip().success(() => {
          this.correctionShow = false
          this.btnloading = false
          this.$parent.ordered()
          this.inited()
        }).error(() => { }).get()
      },
      checkAllGroupChange(data) {
        console.log(data)
        if (data === '签约主体红冲') {
          this.redCorrection = 1
        } else if (data === '金额红冲') {
          this.redCorrection = 2
        }
        // 以下为多选时判断
        // 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
        // }
      },
      onPaymentVisibleChange(val){
        console.log(val)
        if(val) {
          this.getPayOrderInfo('query')
        }
      },
      getPayOrderInfo(doType, money, payWay) {
        this.paymentLoading = true
        console.log(money, payWay, 'order_code')
        ajaxGetPayCode({
          orderCode: this.orderDetail.order_code,
          money: money ? Math.round(Number(money) * 10000) / 100 : undefined,
          payWay: payWay ? Number(payWay) : undefined,
          doType
        }).then(res => {
          console.log(res,'res')
          if(res.error_code === 0 && res.data) {
            if(doType === 'query') {
                this.paymentForm.money = res.data.money / 100
                this.paymentForm.product = res.data.product
                this.paymentForm.account = res.data.account
                this.paymentForm.noPayment = res.data.money / 100
                this.getPayOrderInfo('getPay', this.paymentForm.money, this.paymentForm.mode)
              } else if (doType === 'getPay') {
                this.paymentLoading = false
                // this.paymentForm.imgCode = res.data.product
                this.paymentForm.expire = res.data.expire
                QRCode.toDataURL(res.data.product,{
                  color: {
                    dark:"#000000",
                    light:"#FFFFFF"
                  }
                }).then((url) => {
                  // 获取到url后即可在页面使用--二维码图片
                  this.paymentForm.imgCode = url
                }).catch((e) => {
                  console.log('e', e)
                  this.$toast('二维码转换失败')
                })
              }
          }
        })
        
      },
      onChangePayWay(val){
        this.paymentForm.mode = val
        this.paymentLoading = true
        this.getPayOrderInfo('getPay', this.paymentForm.money, this.paymentForm.mode)
      },
      onChangePayMoney: debounce(function () {
        // this.paymentForm.money = formatInputMoney(this.paymentForm.money)
        const noPayment = this.paymentForm.noPayment
        const currentMoney = Number(this.paymentForm.money)
        console.log(noPayment, currentMoney, 'change money');
        // 正则表达式：只允许数字，小数点，且小数点后最多两位
        const regex = /^\d+(\.\d{1,2})?$/;
        // 如果输入的值不匹配正则表达式，则将其设置为上一个匹配的值
        if (!regex.test(this.paymentForm.money)) {
          // this.paymentForm.money = this.paymentForm.money.replace(/[^0-9.-]+/g, '');
          return this.$toast('只能输入正数数字，小数点，且小数点后最多两位')
        }
        if (currentMoney > noPayment || !currentMoney) {
          this.paymentLoading = true
          setTimeout(() => {
            this.paymentForm.money = noPayment
            this.getPayOrderInfo('getPay', this.paymentForm.money, this.paymentForm.mode)
          }, 500)
          return this.$toast(`0<付款金额≤${noPayment}`)
        }
        this.getPayOrderInfo('getPay', this.paymentForm.money, this.paymentForm.mode)
      }, 500),
      // dom转图片
      async convertToImage() {
        try {
          const canvas = await html2canvas(this.$refs.screenshotRef);
          this.imageUrl = canvas.toDataURL('image/png');
        } catch (error) {
          console.error('转换出错:', error);
        }
      },
      async onSavePaymentCode() {
        if (this.paymentLoading) return
        await this.convertToImage()
        await copyImage(this.imageUrl)
        this.$toast('付款码复制成功')
        this.paymentCodeShow = false
      }
    },
    data() {
      return {
        paymentCodeShow: false,
        btnloading: false,
        pa_dis: false,
        performanceDis: false,
        permissionActivationShow: false,
        performanceShow: false,
        iShow: false,
        backShow: false,
        pShow: false,
        sShow: false,
        tShow: false,
        correctionShow: false,
        bigCorrection: false,
        redCorrection: 4,
        isDisable: false,
        invoice: {
          type: ''
        },
        invoType: [
          { v: '1', n: '普通发票（纸质发票）' },
          { v: '2', n: '普通发票（电子发票）' },
          { v: '3', n: '专用发票（纸质发票）' }
        ],
        contract: {
          contractFileUrl: '',
          contract_archive_num: '',
          contract_archive_time: ''
        },
        funds: {
          sum: '',
          shCode: ''
        },
        permissionActivation: {
          phone: '',
          startTime: '',
          orderCode: ''
        },
        saleTable: [
          {
            title: '销售人员',
            slot: 'name',
            width: 150
          },
          {
            title: '业绩归属部门',
            slot: 'saler_dept',
            width: 200
          },
          {
            title: '销售业绩（元）',
            slot: 'money',
            width: 200
          },
          {
            title: '销售渠道',
            slot: 'channel',
            width: 200
          }
        ],
        ajaxinitSalelist: [],
        reasonList: [],
        saleTableData: [],
        performanceFrom: {
          changeReason: "",
          saleMoney: ""
        },
        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' }
          ]
        },
        paymentForm: {
          mode: '1',
          account: '',
          product: '',
          imgCode: '',
          aliSrc:'',
          expire: 0,
          noPayment: 0
        },
        paymentLoading: true,
        displayMap: {},
        imageUrl: null // 转换后的图片URL
      }
    },
    computed: {
      ...mapGetters(['channelListGetters', 'channelMapGetters']),
      signingSubject() {
        return this.orderDetail.signing_subject === 'h01' ? '北京拓普丰联信息科技股份有限公司' : '北京剑鱼信息技术有限公司'
      },
      saveCodeDisabled() {
        return !(!this.paymentLoading && this.paymentForm.money && this.paymentForm.imgCode)
      }
    }
  }
</script>
<style lang="scss" scoped>
.correctionLabel {
  font-size: 16px;
  font-weight: bold;
  color: red;
  margin-bottom: 10px;
}
.payment-code-model{
  top: 50px;
  .ivu-modal-body{
    line-height: normal!important;
    padding: 16px;
    max-height: 620px!important;
  }
  .ivu-form-item{
    margin-bottom: 8px;
  }
  .ivu-modal-footer{
    border-top: 0;
    padding: 0!important;
  }
  .ali-iframe{
    width: 280px;
    height: 280px;
    padding: 14px 0 0 14px;
    border: 0;
  }
}
.guide-tip{
  padding: 12px;
}
.table-order1{
  .ivu-form-item-content tr td:nth-child(3) .ivu-input {
    height: 36px!important;
    border-radius: 6px!important;
  }
}
.screenshot-container{
  width: 100%;
  max-width: 380px;
  padding: 24px 28px;
  margin: 0 auto;
  height: auto;
  background: linear-gradient(180deg, #2ABED1 0%, #87DFEA 100%);
  //transform: scale(0.9);
  .screenshot-logo{
    display: block;
    width: 130px;
    height: 34px;
    margin: 0 auto 16px;
  }
  .screenshot-content{
    padding: 20px 0;
    background: #fff;
    border-radius: 20px;
  }
  .screenshot-info{
    margin: 0 18px;
    padding: 8px 16px;
    background: #F5F6F7;
    border-radius: 12px;
    text-align: center;
    color: #171826;
    font-size: 16px;
    p{
      line-height: 24px;
    }
  }
  .screenshot-money{
    display: flex;
    align-items: center;
    justify-content: center;
    padding-top: 16px;
    font-size: 15px;
    color: #171826;
    .num{
      margin-left: 8px;
      font-size: 24px;
      color: #FB483D;
    }
  }
  .screenshot-code{
    width: 200px;
    height: 200px;
    margin: 0 auto;
    img{
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
  .screenshot-tip{
    font-size: 16px;
    line-height: 24px;
    color: #171826;
    text-align: center;
  }
  .screenshot-date{
    margin-top: 2px;
    font-size: 14px;
    line-height: 20px;
    color: #5F5E64;
    text-align: center;
  }
}
</style>
