<template>
  <div class="app-container">
    <div class="head-container">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="" prop="orderId">
              <el-input
                v-model="queryParams.orderId"
                placeholder="请输入订单编号"
                clearable
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item label="" prop="productName">
              <el-input
                v-model="queryParams.productName"
                placeholder="请输入推荐人姓名"
                clearable
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item label="" prop="platform">
              <el-select
                v-model="queryParams.platform"
                placeholder="是否是直播带货订单"
                clearable
                :fit-input-width="true"
                style="width: 150px"
              >
                <el-option label="是" :value="1" />
                <el-option label="否" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item label="" prop="customAccount" label-width="110px">
              <el-input
                v-model="queryParams.customAccount"
                placeholder="请输入带货产品名称"
                clearable
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item label="时间筛选：" prop="timeType" class="datepicker">
              <el-select
                v-model="queryParams.timeType"
                placeholder="时间筛选"
                clearable
                class="selectbox"
                :fit-input-width="true"
                style="width: 150px"
              >
                <el-option label="下单时间" :value="1" />
                <el-option label="支付时间	" :value="2" />
                <el-option label="生效时间" :value="3" />
                <el-option label="到期时间	" :value="4" />
                <el-option label="申请退款时间" :value="5" />
                <el-option label="退款成功时间" :value="6" />
              </el-select>
            </el-form-item>
            <el-form-item label="" prop="" class="datepicker">
              <el-date-picker
                v-model="dateVale"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                size="small"
              />
            </el-form-item>
            <el-form-item style="margin-left: 10px">
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-search"
                @click="handleSearch(1)"
              >查询</el-button>
              <el-button
                size="mini"
                icon="el-icon-refresh-right"
                @click="handleReset('queryFormRef')"
              >重置</el-button>
              <el-button
                size="mini"
                type="primary"
                :loading="downloadLoading"
                @click="toExport"
              >导出</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>
    <!--表格渲染-->
    <el-table v-loading="loading" :data="data" style="width: 100%">
      <el-table-column
        align="center"
        type="index"
        width="60"
        label="序号"
        fixed="left"
      />
      <el-table-column
        prop="orderId"
        label="订单编号"
        fixed="left"
        width="180px"
      />
      <el-table-column
        prop="customCode"
        label="订单来源渠道"
        fixed="left"
        width="120px"
      />
      <el-table-column
        prop="customMobile"
        label="微信/支付宝订单号"
        width="120px"
      />
      <el-table-column prop="customAccount" label="客户姓名" width="110px" />
      <el-table-column prop="customName" label="客户营业部" width="130px" />
      <el-table-column prop="productType" label="资金账号" width="110px" />
      <el-table-column
        prop="productId"
        :label="settingToC ? '客户账号' : '客户手机号'"
        width="100px"
      />
      <el-table-column prop="productName" label="客户风测等级" width="100px" />
      <el-table-column prop="categoryName" label="产品名称" width="110px" />
      <el-table-column prop="moduleStart" label="	产品类型" width="180px" />
      <el-table-column prop="moduleEnd" label="产品风险等级" width="180px" />
      <el-table-column prop="payType" label="创建者" width="100px" />

      <el-table-column prop="payId" label="所属分公司" width="260px" />
      <el-table-column prop="payTime" label="所属营业部" width="180px" />
      <el-table-column prop="totalPrice" label="是否是直播带货订单">
        <template #default="scope">
          {{ (scope.row.totalPrice / 100).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="payPrice" label="带货直播名称" width="100px">
        <template #default="scope">
          {{ (scope.row.payPrice / 100).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="rate" label="支付方式" width="100px">
        <template #default="scope">
          {{ scope.row.rate ? `${scope.row.rate * 1000}‰` : "-" }}
        </template>
      </el-table-column>
      <el-table-column prop="couponId" label="服务时长" width="180px" />
      <el-table-column label="扣款方式" width="180px">
        <template #default="scope">
          <span>{{ coupon_type_map[scope.row.couponType] || "" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="产品定价" width="180px">
        <template #default="scope" />
      </el-table-column>

      <el-table-column prop="couponId" label="订单金额" width="180px">
        <template #default="scope" />
      </el-table-column>

      <el-table-column prop="isRenewal" label="实际支付金额" width="110px">
        <template #default="scope" />
      </el-table-column>
      <el-table-column
        prop="customRiskLevel"
        label="是否使用优惠券"
        width="110px"
      >
        <template #default="scope" />
      </el-table-column>
      <el-table-column prop="productRiskLevel" label="优惠券名称" width="110px">
        <template #default="scope" />
      </el-table-column>
      <el-table-column prop="productPeriod" label="订单状态" width="100px">
        <template #default="scope" />
      </el-table-column>
      <el-table-column prop="refereeName" label="是否续订" width="100px" />
      <el-table-column prop="platform" label="推荐人姓名" width="110px" />

      <el-table-column prop="categoryId" label="推荐人工号" width="100px" />

      <el-table-column prop="channel" label="下单时间" width="90px" />
      <el-table-column prop="campaign" label="支付时间" width="110px" />
      <el-table-column prop="status" label="生效时间" width="100px">
        <template #default="scope" />
      </el-table-column>
      <el-table-column prop="orderTime" label="到期时间" width="180px" />
      <el-table-column prop="updateTime" label="权限状态" width="180px" />
      <el-table-column prop="refundApply" label="退款金额" width="100px" />
      <el-table-column prop="refundAmount" label="申请退款时间" width="110px">
        <template #default="scope" />
      </el-table-column>
      <el-table-column prop="refundReason" label="退款成功时间" width="100px" />
      <el-table-column
        prop="refundApplyTime"
        label="退款审核时间"
        width="180px"
      />
      <el-table-column prop="operator" label="退款理由" width="110px" />
    </el-table>

    <!--分页组件-->
    <el-pagination
      :total="total"
      :current-page="queryParams.current"
      :page-size="queryParams.size"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import { mapGetters, mapState } from "vuex";
import dayjs from "dayjs";
import {
  queryOrderList,
  toRefundApplyCheck,
  toRefundApply,
  toRefundForce,
  unSubscribe
} from "@/api/order";
import {
  PAY_TYPE_WORDS,
  RENEWAL_MAP,
  RISK_LEVELS,
  CHANNEL_MAP,
  FREE_ORDER_CAMPAIGN_MAP,
  PAY_STATUS_WORDS,
  PAY_STATUS_WORDS_TY,
  PAY_CYCLE,
  COUPON_TYPE_MAP
} from "@/utils/options";
export default {
  name: "",
  data() {
    const checkAmount = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入退款金额"));
      } else if (value > this.refundParams.amount / 100 || value < 0) {
        callback(
          new Error(`请输入大于0小于${this.refundParams.amount / 100}的数字`)
        );
      } else {
        callback();
      }
    };
    return {
      total: 1,
      loading: false,
      data: [],
      pay_type_words: PAY_TYPE_WORDS,
      renewal_map: RENEWAL_MAP,
      risk_levels: RISK_LEVELS,
      channel_map: CHANNEL_MAP,
      free_order_campaign_map: FREE_ORDER_CAMPAIGN_MAP,
      pay_status_words: PAY_STATUS_WORDS,
      pay_status_words_ty: PAY_STATUS_WORDS_TY,
      pay_cycle: PAY_CYCLE,
      coupon_type_map: COUPON_TYPE_MAP,
      queryParams: {
        productName: "",
        categoryId: undefined,
        channel: undefined,
        current: 1,
        customAccount: "",
        customRiskLevel: undefined,
        endTime: "2023-03-08 17:20:24",
        isRenewal: undefined,
        matching: undefined,
        moduleStatus: undefined,
        orderId: "",
        payType: undefined,
        platform: undefined,
        productPeriod: undefined,
        productType: undefined,
        refereeId: "",
        size: 10,
        startTime: "2021-03-08 17:20:24",
        status: undefined,
        timeType: undefined
      },
      dateVale: "",
      refundDialog: {
        title: "",
        visible: false
      },
      checkRefundDialog: {
        title: "",
        visible: false
      },
      checkRefundParams: {
        orderId: "", // 订单ID
        refundAmount: 0, // 退款金额，
        checkStatus: "", // 审核状态 0：驳回 1：申请中 2：通过
        checkReason: "" // 审核意见
      },
      refundParams: {
        orderId: "", // 订单ID
        amount: 0, // 订单金额
        refundAmount: 0, // 退款金额，
        refundReason: "" // 申请退款原因
      },
      refundRules: {
        refundAmount: [
          {
            validator: checkAmount,
            type: "number",
            min: 0,
            required: true,
            trigger: "change"
          }
        ]
      },
      checkRefundRules: {
        checkStatus: [
          {
            required: true,
            message: "请选择审核状态",
            trigger: "change"
          }
        ]
      }
    };
  },
  computed: {
    ...mapGetters(["user"]),
    ...mapState({
      settingToC: state => state.settings.settingToC
    })
  },
  watch: {},
  created() {
    this.dateVale = [
      dayjs()
        .subtract(1, "months")
        .format("YYYY-MM-DD"),
      dayjs().format("YYYY-MM-DD")
    ];
  },
  mounted() {
    this.queryOrderList();
  },

  methods: {
    // 查询订单
    queryOrderList() {
      this.loading = true;
      // this.$set(
      //   this.queryParams,
      //   'startTime',
      //   moment(this.queryParams.startTime).format('YYYY-MM-DD HH:mm:ss')
      // )
      // const isEndTime = new Date(this.queryParams.endTime)
      // isEndTime.setHours(23)
      // isEndTime.setMinutes(59)
      // isEndTime.setSeconds(59)
      // this.$set(
      //   this.queryParams,
      //   'endTime',
      //   moment(isEndTime).format('YYYY-MM-DD HH:mm:ss')
      // )

      this.queryParams.startTime = dayjs(this.dateVale[0]).format(
        "YYYY-MM-DD 00:00:00"
      );
      this.queryParams.endTime = dayjs(this.dateVale[1]).format(
        "YYYY-MM-DD 23:59:59"
      );

      queryOrderList(this.queryParams).then(data => {
        this.data = data.data.list;
        this.total = data.data.total;
        this.loading = false;
      });
    },
    handleSearch(current) {
      this.$set(
        this.queryParams,
        "current",
        current || this.queryParams.current
      );
      this.queryOrderList();
    },
    handleReset(formName) {
      this.$refs[formName].resetFields();
      this.queryOrderList();
    },
    submitRefundForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.toRefundApplyMethod();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    resetRefundForm(formName) {
      this.$refs[formName].resetFields();
      this.$set(this.refundDialog, "visible", false);
    },

    resetCheckRefundForm(formName) {
      this.$refs[formName].resetFields();
      this.$set(this.checkRefundDialog, "visible", false);
    },

    // 审核退款提交
    submitCheckRefundForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.toRefundApplyCheckMethod();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    async toRefundApplyCheckMethod() {
      const { code } = await toRefundApplyCheck(this.checkRefundParams);
      if (code === 0) {
        this.$message({
          message: "审核退款成功",
          type: "success"
        });
        this.resetCheckRefundForm("checkRefundFormRef");
        this.queryOrderList();
      } else {
        this.$message({
          message: "审核退款失败",
          type: "error"
        });
      }
    },
    // 申请退款提交
    async toRefundApplyMethod() {
      const params = {
        orderId: this.refundParams.orderId,
        refundAmount: this.refundParams.refundAmount * 100,
        refundReason: this.refundParams.refundReason
      };
      if (this.refundDialog.title === "申请退款") {
        const { code } = await toRefundApply(params);
        if (code === 0) {
          this.$message({
            message: "申请退款成功",
            type: "success"
          });
          this.resetRefundForm("refundFormRef");
          this.queryOrderList();
        } else {
          this.$message({
            message: "申请退款失败",
            type: "error"
          });
        }
      } else if (this.refundDialog.title === "强制退款") {
        const { code } = await toRefundForce(params);
        if (code === 0) {
          this.$message({
            message: "强制退款成功",
            type: "success"
          });
          this.resetRefundForm("refundFormRef");
          this.queryOrderList();
        } else {
          this.$message({
            message: "强制退款失败",
            type: "error"
          });
        }
      }
    },

    // 退款弹窗
    showEdit(row, title) {
      this.$set(this.refundDialog, "title", title);
      this.$set(this.refundDialog, "visible", true);
      this.$set(this.refundParams, "orderId", row.orderId);
      this.$set(this.refundParams, "amount", row.payPrice);
    },
    // 审核窗口
    showCheck(row, title) {
      this.$set(this.checkRefundDialog, "title", title);
      this.$set(this.checkRefundDialog, "visible", true);
      this.$set(this.checkRefundParams, "orderId", row.orderId);
      this.$set(this.checkRefundParams, "refundAmount", row.refundAmount);
    },
    handleCurrentChange(val) {
      this.$set(this.queryParams, "current", val || 1);
      this.queryOrderList();
    },
    handleSizeChange(val) {
      this.$set(this.queryParams, "size", val);
      this.$set(this.queryParams, "current", 1);
      this.queryOrderList();
    },
    async unSubscribeFn(val) {
      const ret = await unSubscribe({ orderId: val });
      if (ret.code === 0) {
        this.$message({
          message: "解约成功！",
          type: "success"
        });
        this.queryOrderList();
      } else {
        this.$message({
          message: "解约失败！",
          type: "error"
        });
      }
    }
  }
};
</script>

<style scoped lang="scss">
.compress {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.el-pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

::v-deep.el-input__suffix {
  margin-right: 3px;
}

.head-down {
  display: flex;
  align-items: baseline;
}
</style>
