<template>
  <div>
    <crud-template v-if="itemStart" class="as-weight" :ref="(el) => crudRef = el" :home-data="field"
      @btnSearch="btnSearch" @refreshLeft="refreshLeft" :tableData="tableData" @CurrentChange="handleCurrentChange"
      @handleRemark="handleRemark" @cancel="cancel" @download="download" @pageSizeChange="(val) => {
      field.paging.currentPage = 1
      field.paging.pageSize = val
      getList()
    }">
      <template #search>
        <el-input maxlength="60" v-trim clearable v-model="searchForm.externalOrderNo" style="width: 160px;"
          placeholder="请输入支付单号" />
        <el-input
          maxlength="60"
          v-trim
          clearable
          v-model="searchForm.vehiclePlate"
          placeholder="请输入车牌号"
          style="width: 320px"
        >
          <template #append>
            <el-select
              clearable
              v-model="searchForm.vehiclePlatecolor"
              placeholder="请选择车牌颜色"
              style="width: 150px"
            >
              <el-option
                :label="item.label"
                :key="item.label"
                :value="item.value"
                v-for="item in VEHICLE_COLOR_TYPE"
              />
            </el-select>
          </template>
        </el-input>
        <el-input maxlength="60" v-trim clearable v-model="searchForm.cardId" style="width: 160px;"
          placeholder="请输入卡号" />
          <el-select
          clearable
          v-model="searchForm.status"
          placeholder="请选择退费状态"
          style="width: 200px"
        >
          <el-option
            v-for="item in statusList"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select
          clearable
          v-model="searchForm.businessPort"
          placeholder="请选择退费业务"
          style="width: 200px"
        >
          <el-option
            v-for="item in portList"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-date-picker unlink-panels clearable v-model="value1" type="daterange" range-separator="到"
          start-placeholder="创建开始日期" end-placeholder="创建结束日期" value-format="YYYY-MM-DD" format="YYYY-MM-DD"
          @change="dateChangeHandle" :clearable="true" />
      </template>
      <template #operation="{ scope }">
        <el-button type="primary" @click="confirmRefund(scope.row)" size="small"
          v-if="scope.row.status === 'AUDITED' && IsPermission(route, 'REFUND_CONFIRM')">退款确认</el-button>
        <el-button type="primary" @click="handleCheck(scope.row.id, 'REFUNDED')" size="small"
          v-if="scope.row.status === 'ARTIFICIAL' && IsPermission(route, 'REFUNDED')">已退款</el-button>
        <el-button type="warning" @click="handleCheck(scope.row.id, 'REFUNDFAILED')" size="small"
          v-if="scope.row.status === 'ARTIFICIAL' && IsPermission(route, 'NO_REFUND')">未退款</el-button>
      </template>
      <template #dialog>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="支付单号" label-align="right" align="center">
            {{ rowData.externalOrderNo }}
          </el-descriptions-item>
          <el-descriptions-item label="ETC卡号" label-align="right" align="center">
            {{ rowData.cardId }}
          </el-descriptions-item>
          <el-descriptions-item label="车牌号" label-align="right" align="center">
            {{ rowData.vehiclePlate }}
          </el-descriptions-item>
          <el-descriptions-item label="车牌颜色" label-align="right" align="center">
            {{ getDictLabel(VEHICLE_COLOR_TYPE, rowData.vehiclePlatecolor) }}
          </el-descriptions-item>
          <el-descriptions-item label="金额（元）" label-align="right" align="center">
            {{
              rowData.amount === null ? 0 + "元" : rowData.amount * 0.01 + "元"
            }}
          </el-descriptions-item>
          <el-descriptions-item label="状态" label-align="right" align="center">
            {{ getDictLabel($storeinitData.state.dictData['REFUND_STATUS'], rowData.status) }}
          </el-descriptions-item>
          <el-descriptions-item label="业务端口" label-align="right" align="center">
            {{ getDictLabel(portList, rowData.businessPort) }}
          </el-descriptions-item>
          <el-descriptions-item label="申请时间" label-align="right" align="center">
            {{ rowData.insertTime ? rowData.insertTime.replaceAll("T", " ") : ""}}
          </el-descriptions-item>
          <el-descriptions-item v-if="rowData.salesmanNickName !== null" label="业务员" label-align="right" align="center">
            {{ rowData.salesmanNickName }}
          </el-descriptions-item>
          <el-descriptions-item label="联系人姓名" label-align="right" align="center">{{ rowData.userName
            }}</el-descriptions-item>
          <el-descriptions-item label="手机号" label-align="right" align="center">{{ rowData.userMobile
            }}</el-descriptions-item>
          <el-descriptions-item label="退费方式" label-align="right" align="center">
            {{ getDictLabel(refundOperateTypeList, rowData.operateType) }}
          </el-descriptions-item>
          <el-descriptions-item
            v-if="rowData.operateType === 'ORIGINAL'"
            label="原路退回方式"
            label-align="right"
            align="center"
          >
            {{ rowData.payReturnType ?? "---" }}
          </el-descriptions-item>
        </el-descriptions>

        <el-descriptions title="银行卡退费信息" v-if="rowData.operateType === 'BANK'" :column="3" border>

          <el-descriptions-item label="开户行" label-align="right" align="center">
            {{ getDictLabel(bankTypeList, rowData.bankType) }}
          </el-descriptions-item>
          <el-descriptions-item label="银行卡号" label-align="right" align="center">
            {{ rowData.bankCardId }}
          </el-descriptions-item>
          <el-descriptions-item label="开户行所在的省" label-align="right" align="center">
            {{ rowData.province }}
          </el-descriptions-item>
          <el-descriptions-item label="开户行所在的市" label-align="right" align="center">
            {{ rowData.sell }}
          </el-descriptions-item>
          <el-descriptions-item label="开户人名称" label-align="right" align="center">
            {{ rowData.cusName }}
          </el-descriptions-item>
          <el-descriptions-item label="开户用户类型" label-align="right" align="center">
            {{ getDictLabel(cusTypeList, rowData.cusType) }}</el-descriptions-item>
          <el-descriptions-item label="开户人联系方式" label-align="right" align="center">
            {{ rowData.cusTel }}
          </el-descriptions-item>

          <el-descriptions-item label="开户行支行名称" label-align="right" align="center">
            {{ rowData.branchName }}
          </el-descriptions-item>

        </el-descriptions>
        <el-descriptions title="实际退费信息" v-if="refundBtn || rowData.refundAmount" :column="3" border>
          <el-descriptions-item label="实际退费金额(元)" label-align="right" align="center">
            {{ rowData.refundAmount }}
          </el-descriptions-item>
        </el-descriptions>


        <el-descriptions title="付费银行账号信息" v-if="rowData.operateType === 'BANK'" :column="2" border>

          <el-descriptions-item label="付费银行" label-align="right" align="center" v-if="refundBtn">
            <el-select clearable v-model="rowData.paymentBankType" :disabled="!refundBtn" class="m-2"
              placeholder="请选择付费银行">
              <el-option v-for="item in bankTypeList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-descriptions-item>
          <el-descriptions-item label="付费银行卡号" label-align="right" align="center" v-if="refundBtn">
            <el-input maxlength="60" v-trim clearable v-model="rowData.paymentBankCardId" :disabled="!refundBtn"
              placeholder="请输入银行卡号" />
          </el-descriptions-item>
          <el-descriptions-item label="付费银行" label-align="right" align="center" v-if="!refundBtn">
            {{ getDictLabel(bankTypeList, rowData.paymentBankType) }}
          </el-descriptions-item>
          <el-descriptions-item label="付费银行卡号" label-align="right" align="center" v-if="!refundBtn">
            {{ rowData.paymentBankCardId }}
          </el-descriptions-item>
        </el-descriptions>
      </template>
      <template #footer>
        <el-button type="primary" @click="refundSubmit(rowData.id, '退费确认')" v-if="refundBtn">退费确认</el-button>
        <el-button type="primary" @click="refundSubmit(rowData.id, '重新审核')" v-if="refundBtn">重新审核</el-button>
        <el-button type="primary" @click="cancellation" v-if="refundBtn">取消</el-button>
      </template>
    </crud-template>
  </div>
</template>

<!-- 退款管理 -->
<script lang="ts" setup>
  // @ts-ignore crudFrom模板
  import CrudTemplate from '@/crud/index.vue'
  import { reactive, ref, toRaw, getCurrentInstance, onMounted, computed } from 'vue'
  import { ElNotification, ElMessage } from "element-plus";
  import Cookies from 'js-cookie'
  import { useDebounce, getDictLabel } from "@/utils/utils";
  import BaseService from "@/utils/baseService";
  import { IHttpResponse, IObject } from "@/types/interface";
  import { logListApi } from "@/api/api";
  import { cloneDeep } from 'lodash';
  import { refundPageApi, refundQueryApi, refundExamineApi, refundOncemoreApi, refundCheckApi, refundConfirmApi, refundExportApi } from "@/api/onlineBusinessHall/salesAndQuery";
  import $storeinitData from "@/store/initData";
  import { useRoute } from 'vue-router';
  import { IsPermission } from "@/router/routerUtil";
  import { getDefaultTime } from '../../exportFn';
  import moment from 'moment';
  //或取路由传入过来的对象数据
  const route = useRoute();
  const crudRef = ref()
  const itemStart = ref(true)
  const tableType = ref(null);
  const refundBtn = ref(false);
  const searchForm = ref({
    externalOrderNo: '',
    cardId: '',
    startTime: '',
    endTime: '',
    vehiclePlate: '',
    vehiclePlatecolor: '',
    status: '',
  })
  const statusList = computed(() => {
    return $storeinitData.state.dictData['REFUND_STATUS'] || []
  })
  const portList = computed(() => {
    return $storeinitData.state.dictData['REFUND_BUSINESS'] || []
  })
  const refundOperateTypeList = computed(() => {
    return $storeinitData.state.dictData['REFUND_OPERATE_TYPE'] || []
  })
  const cusTypeList = computed(() => {
  return $storeinitData.state.dictData['ETC_USER_TYPE'] || []
})
  const bankTypeList = computed(() => {
    return $storeinitData.state.dictData['BANK_TYPE'] || []
  })
  const VEHICLE_COLOR_TYPE = computed(() => {
  return $storeinitData.state.dictData['VEHICLE_COLOR_TYPE'] || []
}) //车牌颜色
  const refundNum = ref(0)

  const tableData = ref([] as any[]);
  const rowData = ref({});
  const initItem = {
    id: "",
  };
  const addForm: any = ref(initItem);
  //表单数据配置
  const field = ref({
    tabSize: 'small', //Table 的尺寸 large / default /small (默认default)
    searchShow: IsPermission(route, 'QUERY_BASE'), //是否显示搜索模块(默认false)
    border: true, //是否添加边框(默认false)
    dialogCustom: true, //自定义Dialog (默认false)
    dialogFooter: true, //隐藏弹窗页脚显示 (默认false)
    dialogWidth: '60%', //dialog宽度 (默认40%)
    crudShow: true, //是否显示CURD操作栏 (默认true)
    crudChildShow: true, //是否显示CURD子操作栏 (默认true)
    paginStart: true, //是否显示分页查询 (默认false)
    isPageSizes: true,
    pageLayout: 'total, sizes, prev, pager, next',
    titleDialog: "", //table 标题
    tableOperation: true,
    paging: {
      pageSize: 10,
      currentPage: 1,
      total: 0
    },
    crud: {
      add: false,
      edit: false,
      delete: false,
      derive: false,
      search: false,
      refresh: false,
    },
    searchOperation: {
      isDownload: true,
      isAdd: false,
      isTransferMachine: false
    },
    tableSize: -1,
    operateShow: true, //是否为表格添加操作栏(默认true)
    operateTitle: '操作', //操作栏标题(默认为"")
    operateFixed: false, //操作栏是否固定(默认false)
    operateWidth: '150', //操作栏宽度
    operate: {
      edit: false, //是否编辑(默认true)
      delete: false, //是否删除(默认true)
      announcement: false, // 公告
      remark: true, // 详情
      forbidden: false, // 禁用
      enable: false, // 启用
      authorization: false, // 授权
      cancel: false,// 取消订单
      writeOff: false,// 注销
      make: false,// 补缴
    },
    extend: [
      {
        type: 'index',
        label: '序号',
      },
    ],
    field: [
      {
        label: '支付单号',
        prop: 'externalOrderNo',
      },
      {
        label: '卡号',
        prop: 'cardId',
      },
      {
        label: '车牌号',
        prop: 'vehiclePlate',
      },
      {
        label: '车牌颜色',
        prop: 'vehiclePlatecolor',
        funRuleStarts: true,
        funRule: (val) => {
          return getDictLabel(VEHICLE_COLOR_TYPE, val)
        },
    },
      {
        label: '金额(元)',
        prop: 'amount',
        unit: "元",
        funRuleStarts: true,
        funRule: (val: any) => {
          var m = 0;
          var s1 = val.toString();
          var s2 = '0.01'.toString();
          try {
            m += s1.split(".")[1].length;
          } catch (e) { }
          try {
            m += s2.split(".")[1].length;
          } catch (e) { }

          return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
          // return val === null ? 0+"元" : val*0.01+"元"
        },
      },
      {
        label: '状态',
        prop: 'status',
        width: "170",
        funRuleStarts: true,
        funRule: (val: any) => {
          return getDictLabel(statusList.value, val)
        },
      },
      {
        label: '业务端口',
        prop: 'businessPort',
        width: "170",
        funRuleStarts: true,
        funRule: (val: any) => {
          return getDictLabel(portList.value, val)
        },
      },
      {
        label: '操作员',
        prop: 'salesmanNickName',
      },
      {
      prop: 'refundTime',
      label: '退款时间',
      width: '170px',
      funRuleStarts: true,
      funRule: (val: any) => {
        if (val) {
          return val.replaceAll('T', ' ')
        }
        return val
      },
    },
      {
        prop: 'insertTime',
        label: '创建时间',
        width: '170px',
        funRuleStarts: true,
        funRule: (val: any) => {
          if (val) {
            return val.replaceAll('T', ' ')
          }
          return val
        },
      },
      {
        prop: 'auditTime',
        label: '审核时间',
        width: '170px',
        funRuleStarts: true,
        funRule: (val: any) => {
          if (val) {
            return val.replaceAll('T', ' ')
          }
          return val
        },
      },
    ],
  })
  // 搜索按钮
  function btnSearch() {
    field.value.paging.currentPage = 1;
    getList();
  }
  // 搜索重置
  function refreshLeft() {
    field.value.paging.currentPage = 1;
    searchForm.value = {
      externalOrderNo: '',
      cardId: '',
      startTime: '',
      endTime: '',
      vehiclePlate: '',
      vehiclePlatecolor: '',
      status: '',
    }
    value1.value = []
    tableData.value = [];
    getList();
  }

  // const defaultTime: [Date, Date] = getDefaultTime('day', 1,'YYYY-MM-DD')
  // const value1: any = ref(defaultTime) // 筛选时间
  const value1 = ref([])
  // 时间
  function dateChangeHandle(val) {
    if (val) {
      searchForm.value.startTime = val[0] + ' 00:00:00';
      searchForm.value.endTime = val[1] + ' 23:59:59';
    } else {
      searchForm.value.startTime = '';
      searchForm.value.endTime = '';
    }
  }
  // function dateChange(time) {
  //   if (time) {
  //     time = moment(time).format("YYYY-MM-DD");
  //   }
  //   return time
  // }
  function download() {

    crudRef.value.tableLoding = true;
    let params: any = {
    }
    let searchFormList = { ...searchForm.value }
    for (let key in searchFormList) {
      if (searchFormList[key]) {
        params[key] = searchFormList[key]
      }

    }
    BaseService.postN('/settlew/api/issue/refund/export', params).then(
      (res: any) => {
      if (res && res.code === 0) {
        let bizContent = res.data
        BaseService.getDownload(import.meta.env.VITE_APP_UPLOAD_URL + bizContent.fileUrl, "退费信息")
        crudRef.value.tableLoding = false;
        getList()
      } else {
        crudRef.value.tableLoding = false;
        ElMessage.error(res.message)
        getList()
      }
    })
  }

  function getList() {
    crudRef.value.tableLoding = true;
    let params: any = {
      pageNo: field.value.paging.currentPage,
      pageSize: field.value.paging.pageSize,
      status: tableType.value
    }
    let searchFormList = { ...searchForm.value }
    for (let key in searchFormList) {
      if (searchFormList[key]) {
        params[key] = searchFormList[key]
      }
    }
    BaseService.postN('/settlew/api/issue/refund/page', params).then((res: any) => {
      if (res && res.statusCode === 0) {
        let bizContent = res.data
        let data = bizContent.result || [];
        console.log("====data", data)
        tableData.value = data;
        crudRef.value.tableLoding = false;
        field.value.paging.total = bizContent.totalCount;
      } else {
        crudRef.value.tableLoding = false;
        ElMessage.error(res.message)
      }
    })
  }
  function handleCurrentChange(val: number) {
    field.value.paging.currentPage = val;
    getList();
  }
  // 导出
  function downloadHandle() {


  }

  // 切换列表
  // function tableTypeChange(val) {
  //     if (val) {
  //         let findItem = radioData.find((item) => item.value === val);
  //         console.log("item", findItem)
  //         if (findItem) {
  //             crudRef.value.tableFrom.field = findItem.fieldData || [];
  //         }
  //         refreshLeft();
  //     }
  // }

  function confirmRefund(row: IObject) {
    getRow(row.id)
    refundBtn.value = true;
    crudRef.value.title = "退款确认";

    crudRef.value.dialogFormVisible = true;
  }
  function cancellation() {
    refundBtn.value = false;
    crudRef.value.dialogFormVisible = false;
  }

  //查看
  function handleRemark(idx: any, row: any) {
    const data = toRaw(row);
    rowData.value = {
    ...data
    // cusType: data.cusType ?? null,
    // bankType: data.bankType ?? null,
    // refundAmount: data.amount ? data.amount * 0.01 : null,
    // operateType: data.operateType ?? ''
  }
    refundBtn.value = false;
  }
  // 获取数据
  function getRow(id: string) {
    // BaseService.postN('/settlew/agencymapping/refundquery', { id: id }).then((res: any) => {
    //   if (res && res.code === 0) {
    //     let bizContent = res.data
    //     let data = bizContent.data || {};
    //     console.log("data:", data)

    //     rowData.value = data;
    //     if (data.cusType !== null) {
    //       rowData.value.cusType = '' + data.cusType;
    //     }
    //     if (data.bankType !== null) {
    //       rowData.value.bankType = '' + data.bankType;
    //     }
    //     if (data.refundAmount !== null) {
    //       rowData.value.refundAmount = data.refundAmount * 0.01;
    //     }
    //   } else {
    //     ElMessage.error(res.message)
    //   }
    // })
  }
  //取消
  function cancel() {
    refundBtn.value = false;
    addForm.value = {
      ...initItem
    }
  }
  // const submitHandle = useDebounce(refundSubmit)
  // 退款审核
  let timer: any = null
  function refundSubmit(id: string, examine: string) {
    if (timer) return
    timer = setTimeout(() => {
      let params: any = {
        id: id,
        censorResult: examine,
        paymentBankType: rowData.value.paymentBankType,
        paymentBankCardId: rowData.value.paymentBankCardId,
        failReason: ""
      }
      let reqApi = '/settlew/api/issue/refund/result';

      BaseService.post(reqApi, params).then((res: any) => {
        if (res && res.code === 0) {
          ElMessage.success("操作成功")
          crudRef.value.dialogFormVisible = false;
          getList()
        } else {
          ElMessage.error(res.message)
        }
      })
      timer = null
    }, 1000)
  }

  function conversion(val: any) {
    var m = 0;
    if (!val) return 0
    var s1 = val.toString();
    var s2 = '0.01'.toString();
    try {
      m += s1.split(".")[1].length;
    } catch (e) { }
    try {
      m += s2.split(".")[1].length;
    } catch (e) { }

    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
    // return val === null ? 0+"元" : val*0.01+"元"
  }
  // 退款核对
  function handleCheck(id: string, examine: string) {

    let params: any = {
      id: id,
      result: examine,
    }
    BaseService.post(refundCheckApi, params).then((res: any) => {
      if (res && res.code === 0) {
        ElMessage.success("操作成功")
        crudRef.value.dialogFormVisible = false;
        getList()
      } else {
        ElMessage.error(res.message)
      }
    })
  }

  onMounted(() => {
    getList();
  })

</script>
<style scoped lang="less">
.data-item {
  display: inline-block;
  padding: 10px;
  border: 1px solid #d7d7d7;
  height: 200px;
  width: 100%;
  overflow-y: auto;
}

.row-wrap {
  margin-bottom: 16px;
}

.col-wrap {
  display: flex;
  align-items: center;

  .label {
    color: #333;
    width: 100px;
    text-align: right;
  }

  &>span:last-child {
    color: #666;
    margin-left: 8px;
  }

}
</style>
