<template>
  <div class="basic-main" style="height: 98%">
    <div class="flex">
      <criteria-paged :model="model" v-ref:paged>
        <criteria partial='criteria' @condition-changed='$parent.selfSearch' v-ref:cri>
          <div novalidate class="form-horizontal select-overspread container-fluid auto" partial>
            <div class="row">
              <!--<div class="col-sm-2 form-group">-->
              <!--<label class="font_normal_body">组织机构:</label>-->
              <!--<res-select :initresid='$parent.$parent.curorgid'-->
              <!--@res-select="$parent.$parent.getorg"-->
              <!--class="select select_list"-->
              <!--restype='organization'-->
              <!--style="width: 60%">-->
              <!--</res-select>-->
              <!---->
              <!--</div>-->
              <res-select-group :show-component="$parent.$parent.initresgroup" :initres="$parent.$parent.initres"
                                @re-res="$parent.$parent.getRes" v-ref:sel></res-select-group>
              <div class="col-sm-2  form-group">
                <label for="startDate" class="font_normal_body">开始日期</label>
                <datepicker id="startDate" placeholder="开始日期"
                            v-model="model.startDate" style="width: 55%"
                            :value.sync="model.startDate"
                            condition="f_datatime >= '{} 00:00:00'"
                            :disabled-days-of-Week="[]"
                            :format="'yyyy-MM-dd'"
                            :show-reset-button="reset">
                </datepicker>
              </div>
              <div class="col-sm-2  form-group">
                <label for="endDate" class="font_normal_body"> 结束日期</label>
                <datepicker id="endDate" placeholder="结束日期"
                            v-model="model.endDate" style="width: 55%"
                            :value.sync="model.endDate"
                            condition="f_datatime <= '{} 23:59:59'"
                            :disabled-days-of-Week="[]"
                            :format="'yyyy-MM-dd'"
                            :show-reset-button="reset">
                </datepicker>
              </div>
              <div class="span" style="float:right;">
                <button class="button_search button_spacing width-60" @click="search()" v-el:cx>查询</button>
                <button class="button_search button_spacing width-60" v-if="$parent.$parent.showallcharge"
                        @click="$parent.$parent.allcharge()" v-el:cx>全部缴费</button>
                <button class="button_search button_spacing width-60" v-if="$parent.$parent.showallcharge || $parent.$parent.showallcharge1"
                        @click="$parent.$parent.allcharge1()" v-el:cx>全部标记退款</button>
                <export-excel :data="$parent.$parent.getCondition"
                              :field="$parent.$parent.getfield"
                              sqlurl="rs/logic/saleExport" progress="saleGetExportProgress" sql-name="WeChatPaydetail"
                              template-name='微信对账查询导出' :choose-col="true"></export-excel>
                <div
                  :class="{'button_shrink_top':$parent.$parent.criteriaShow,'button_shrink_bottom':!$parent.$parent.criteriaShow}"
                  @click="$parent.$parent.hidden()"
                  class="button_spacing"
                  style="float: right">
                </div>
              </div>
            </div>
            <div class="row" v-show="titleShow">
              <div class="col-sm-2  form-group">
                <label class="font_normal_body" title="参数管理:微信收费类型">收费类型</label>
                <v-select
                  v-model="model.chargeType"
                  placeholder='收费类型'
                  condition="f_order_type like '%{}%'"
                  :value.sync="model.chargeType"
                  :options='$parent.$parent.chargeType'
                  close-on-select></v-select>
              </div>
              <div class="col-sm-2  form-group">
                <label class="font_normal_body">支付类型</label>
                <v-select
                  v-model="model.payType"
                  placeholder='支付类型'
                  condition="f_trade_type like '%{}%'"
                  :value.sync="model.payType"
                  :options='$parent.$parent.payType'
                  close-on-select></v-select>
              </div>
              <div class="col-sm-2  form-group">
                <label class="font_normal_body">对账信息</label>
                <v-select
                  v-model="model.letter"
                  placeholder='对账信息'
                  condition="msg like '%{}%'"
                  :value.sync="model.letter"
                  :options='$parent.$parent.letter'
                  close-on-select></v-select>
              </div>
              <div class="col-sm-2 form-group">
                <label class="font_normal_body">用户编号</label>
                <input type="text" class="input_search" style="width: 55%" v-model="model.f_userinfo_code"
                       placeholder='客户编号' condition="f_userinfo_code = '{}'">
              </div>
              <div class="col-sm-2 form-group">
                <label class="font_normal_body">&emsp;订单号</label>
                <input type="text" class="input_search" style="width: 55%" v-model="model.f_transaction_id"
                       placeholder='订单号' condition="f_transaction_id like '%{}%'">
              </div>
            </div>
          </div>
        </criteria>
        <data-grid :model="model" partial='list' class="list_area table_sy" v-ref:grid>
          <template partial='head'>
            <tr>
              <th>序号</th>
              <th>用户编号</th>
              <th>用户姓名</th>
              <th>支付类型</th>
              <th>微信金额</th>
              <th>收费记录金额</th>
              <th style="white-space: nowrap;">交易日期</th>
              <th>燃气方日期</th>
              <th>微信订单号</th>
              <th>收费订单号</th>
              <th>对账信息</th>
              <th>所属公司</th>
              <th>所属部门</th>
              <th>操作人员</th>
              <th>操作</th>
            </tr>
          </template>
          <template partial='body'>
            <td style="text-align: center;">
              <nobr>{{$index+1}}</nobr>
            </td>
            <td style="text-align: center;">
              <nobr>{{row.f_userinfo_code}}</nobr>
            </td>
            <td style="text-align: center;">
              <nobr>{{row.f_user_name}}</nobr>
            </td>
            <td style="text-align: center;">
              <nobr>{{$parent.$parent.$parent.getPayTypeLable(row.f_trade_type)}}</nobr>
            </td>
            <td style="text-align: center;">
              <nobr>{{row.f_total_fee}}</nobr>
            </td>
            <td style="text-align: center;">
              <nobr>{{row.f_collection}}</nobr>
            </td>
            <td style="text-align: center;">
              <nobr>{{row.f_datatime}}</nobr>
            </td>
            <td style="text-align: center;">
              <nobr>{{row.f_operate_date}}</nobr>
            </td>
            <td style="text-align: center;">
              <nobr>{{row.f_transaction_id}}</nobr>
            </td>
            <td style="text-align: center;">
              <nobr>{{row.f_serial_id}}</nobr>
            </td>
            <td style="text-align: center;">{{row.msg}}</td>
            <td style="text-align: center;">{{row.f_orgname}}</td>
            <td style="text-align: center;">{{row.f_depname}}</td>
            <td style="text-align: center;">{{row.f_operator}}</td>

            <td>
              <button type="button" name="button" class="btn btn-link" @click="$parent.$parent.$parent.charge1(row)"
                      v-if="row.msg === '微信单方面账单'">标记已退款</button>
              <button type="button" name="button" class="btn btn-link" @click="$parent.$parent.$parent.charge(row)"
                      v-if="row.msg === '微信单方面账单' && row.f_trade_type == 'JSAPI'">缴费
              </button>
              <!--<button type="button" name="button"  class="btn btn-link" @click="$parent.$parent.$parent.chargecal(row)"-->
              <!--v-if="row.msg === '燃气方单方面账单' && row.maxid!==''&& row.maxid!==null">冲正</button>-->
          </template>
        </data-grid>

      </criteria-paged>
      <table class="table-hover">
        <tr style="position: relative" class="table-bordered">
          <td
            style="display: inline-block;width: auto;border-right: 1px solid #F2F6FA;padding: 0px 10px 0px 10px;color: #5CB95C;font-weight: bold">
            汇总信息
          </td>
          <td
            style="display: inline-block;width: auto;border-right: 1px solid #F2F6FA;padding: 0px 10px 0px 10px;font-weight: bold">
            微信金额汇总:&emsp;{{sumsmodel.f_total_fee}}
          </td>
          <td
            style="display: inline-block;width: auto;border-right: 1px solid #F2F6FA;padding: 0px 10px 0px 10px;font-weight: bold">
            收费金额汇总:&emsp;{{sumsmodel.f_collection}}
          </td>
          <td
            style="display: inline-block;width: auto;border-right: 1px solid #F2F6FA;padding: 0px 10px 0px 10px;font-weight: bold">
            差额汇总:&emsp;{{((sumsmodel.f_total_fee -0) - (sumsmodel.f_collection -0)).toFixed(2)}}
          </td>

        </tr>
      </table>
    </div>


  </div>
</template>
<script>
  import {PagedList} from 'vue-client'
  import Vue from 'vue'

  let readyGen = async function (self) {
    self.getfield = self.config.excelHeaders
    self.$refs.paged.$refs.cri.model.startDate = self.$login.toStandardDateString()
    self.$refs.paged.$refs.cri.model.endDate = self.$login.toStandardDateString()

    self.sumsmodel = self.$refs.paged.$refs.grid.model.sums
  }

  export default {
    title: '微信中间表对账',
    data () {
      return {
        model: new PagedList('rs/sql/WeChatPaydetail', 20,
          {}, {f_collection: '', f_total_fee: ''}),
        config: {
          // 导出列要和查询列相同
          excelHeaders: {
            'f_userinfo_code': '用户编号',
            'f_user_name': '用户姓名',
            'f_trade_type': '支付类型',
            'f_total_fee': '微信金额',
            'f_collection': '收费记录金额',
            'f_datatime': '交易日期',
            'f_operate_date': '燃气方日期',
            'f_transaction_id': '微信订单号',
            'f_serial_id': '收费订单号',
            'msg': '对账信息',
            'f_orgname': '所属公司',
            'f_depname': '所属部门',
            'f_operator': '操作人员'
          }
        },
        payType: [
          {label: '全部', value: ''},
          {label: '微信支付', value: 'JSAPI'},
          {label: '二维码支付', value: 'NATIVE'},
          {label: '付款码支付', value: 'MICROPAY'}
        ],
        letter: [
          {label: '全部', value: ''},
          {label: '微信单方面账单', value: '微信单方面账单'},
          {label: '燃气方单方面账单', value: '燃气方单方面账单'},
          {label: '对账成功', value: '对账成功'}
        ],
        getfield: {},
        criteriaShow: false,
        condition2: '',
        f_orgid: '',
        titleShow : true,
        msg: [],
        resid: [],  // 存放新增的f_files表中id
        // 公司下拉
        // curorgid: [this.$login.f.orgid],
        initres: {
          org: [this.$login.f.orgid],
          dep: [],
          user: []
        },
        initresgroup: ['company', 'department', 'operator'],
        orgCondtionStr: '',
        // 合计数据
        sumsmodel: {},
        showallcharge: false,
        showallcharge1: false
      }
    },
    props: [],
    ready () {
      readyGen(this)
      this.titleShow = this.$appdata.getSingleValue('是否显示筛选框') == null? true : this.$appdata.getSingleValue('是否显示筛选框')
    },
    methods: {
      getPayTypeLable (f_trade_type) {
        for (let row of this.payType) {
          if (row.value == f_trade_type) {
            return row.label
          }
        }
        return f_trade_type
      },
      hidden () {
        this.criteriaShow = !this.criteriaShow
      },
      getorg (val) {
        this.f_orgid = this.$login.convertToIn(val)
        this.f_filialeid = val[0]
      },
      getRes (condition, obj) {
        if (condition.indexOf('f_orgid') > 0) {
          let temp = condition.substring(condition.indexOf("f_orgid in ('") + 13)
          this.f_orgid = temp.substring(temp.indexOf("')") - 4, 3)
        } else {
          this.f_orgid = this.$login.f.orgid
        }
        this.orgCondtionStr = condition
      },

      getotherfooter () {
        // this.$refs.paged.$refs.cri.$refs.exports.otherData=[];
        // this.$refs.paged.$refs.cri.$refs.exports.footerData=[];
        this.other = []
        this.footer = []
        // let exportdata = this.getCondition;
        let otherInData = []
        otherInData.push(`导出时间: ${this.$login.toStandardTimeString()}`)
        let footerData = [], exportfield = this.getfield
        footerData.push('合计')
        let self = this
        for (var field in self.sumsmodel) {
          footerData.push(`${exportfield[field]}合计:${self.sumsmodel[field]}`)
        }
        this.footer.push(footerData)
        this.other.push(otherInData)
      },
      search () {
        this.$refs.paged.$refs.cri.search()
      },
      selfSearch (args) {
        if (!this.f_orgid) {
          this.getorg([this.$login.f.orgid])
        }
        console.log('查询。。。', this.f_orgid)
        this.showallcharge1 = false
        this.showallcharge = false
        if (!this.orgCondtionStr) {
          args.condition = `${args.condition}` + ' and f_orgid = ' + this.$login.f.orgid
        } else {
          args.condition = `${args.condition}` + this.orgCondtionStr
        }
        this.model.params.startDate = this.$refs.paged.$refs.cri.model.startDate
        this.model.params.endDate = this.$refs.paged.$refs.cri.model.endDate
        this.sumsmodel = this.$refs.paged.$refs.grid.model.sums
        this.condition2 = args.condition
        this.model.search(args.condition, args.model)
        // 只有选择微信支付和微信单方面账单时才能全部缴费
        if (this.model.model.letter[0] === '微信单方面账单' && this.model.model.payType[0] === 'JSAPI') {
          this.showallcharge = true
        } else if (this.model.model.payType[0] === 'MICROPAY') {
          this.showallcharge1 = true
        }
      },
      // 系统单方账单，系统可冲正
      async chargecal (row) {
        if (row.f_meter_type === '物联网表' || row.f_meter_type === '机表') {
          let param = {
            f_sell_id: row.maxid,
            f_cancel_reason: '',
            f_orgid: Vue.$login.f.orgid,
            f_orgname: Vue.$login.f.orgs,
            f_depid: Vue.$login.f.depids,
            f_depname: Vue.$login.f.deps,
            f_zoneid: Vue.$login.f.zoneid,
            f_zones: Vue.$login.f.zones
          }
          await Vue.resetpost('rs/logic/commonCancel', {data: param}, {resolveMsg: '撤销成功', rejectMsg: '撤销失败'})
          this.search()
        }
      },
      async allcharge () {
        console.log('1=====>' + this.condition2)
        if (!this.$login.r.find(value => value == '微信缴费权限')) {
          this.$showMessage('当前登录用户没有微信缴费权限, 请联系管理员!')
          return
        }
        let condition = this.condition2
        let item = '已下单'
        await this.$resetpost('rs/logic/dealAllwxBill', {data: {condition: condition, item: item}}, {warnMsg: `确定进行全部缴费吗?`, resolveMsg: '收费成功!!', rejectMsg: '收费出错!!!'})
      },
      async allcharge1 () {
        if (!this.$login.r.find(value => value == '微信缴费权限')) {
          this.$showMessage('当前登录用户没有微信缴费权限, 请联系管理员!')
          return
        }
        let condition = this.condition2
        let item = '已退款'
        await this.$resetpost('rs/logic/dealAllwxBill', {data: {condition: condition, item: item}}, {warnMsg: `确定标记以下所有订单为已退款吗, 该操作无法撤销, 请谨慎操作?`, resolveMsg: '标记为已退款成功', rejectMsg: '标记为已退款失败!!!'})
      },
      // 微信单方账单，系统可缴费(将微信已支付改成已下单,微信会自动扫状态，并插入收费记录)
      async charge (row) {
        if (!this.$login.r.find(value => value == '微信缴费权限')) {
          this.$showMessage('当前登录用户没有微信缴费权限, 请联系管理员!')
          return
        }
        let sql = `update t_weixinreturnxml set f_order_state = '已下单' where id = '${row.id}'`
        await this.$resetpost('rs/logic/runSQL', {data: {sql: sql}}, {warnMsg: `确定进行缴费吗?`, resolveMsg: '收费成功!!', rejectMsg: '收费出错!!!'})
        // this.search()
      },
      // 标记为已退款
      async charge1 (row) {
        let sql = `update t_weixinreturnxml set f_order_state = '已退款' where id = '${row.id}'`
        await this.$resetpost('rs/logic/runSQL', {data: {sql: sql}}, {warnMsg: `确定标记该笔订单为已退款吗, 该操作无法撤销, 请谨慎操作?`, resolveMsg: '标记为已退款成功', rejectMsg: '标记为已退款失败!!!'})
        // this.search()
      },
      modify (row) {
        console.log('返回数据1', row)
        this.$showMessage('确认重置微信支付状态么？', ['confirm', 'cancel']).then((res) => {
          if (res === 'confirm') {
            let data = {
              f_transaction_id: row.f_transaction_id
            }
            this.$resetpost('rs/logic/weChatMeter', data, {resolveMsg: null, rejectMsg: '重置出错!!!'}).then((res) => {
              console.log('返回数据3', res)
              this.$refs.paged.$refs.cri.search()
              this.$showAlert(`重置成功!`, 'success', 4000)
              // this.search()
            }).catch((error) => {
              console.log('重置异常', res)
            })
          }
        })
      }
    },
    events: {
      // 删除Resid数组元素
      'delResid' (val) {
        this.resid.$remove({id: val, f_biobid: ''})
        // this.resid.splice(this.resid.indexOf({id:val,f_biobid:''}),1);
      },
      // 增加Resid数组元素
      'resid' (val) {
        console.log('-=', val)
        this.resid.push({id: val, f_biobid: ''})
      }
    },
    computed: {
      getCondition () {
        return {
          orgid: this.f_orgid,
          startDate: this.$refs.paged.$refs.cri.model.startDate,
          endDate: this.$refs.paged.$refs.cri.model.endDate,
          condition: this.condition2
        }
      },
      chargeType () {
        return [{label: '全部', value: ''}, ...this.$appdata.getParam('微信收费类型')]
      }
    },
    watch: {
      sumsmodel: {
        handler: function (val) {
          this.getotherfooter()
        },
        deep: true
      }
    }
  }
</script>
