<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.numbering"
        placeholder="请输入房票编号"
        class="filter-item"
        clearable
      ></el-input>
      <el-input
        v-model="listQuery.nameB"
        placeholder="请输入用户姓名"
        class="filter-item"
        clearable
      ></el-input>
      <el-input
        v-model="listQuery.idCardB"
        placeholder="请输入身份证号"
        class="filter-item"
        clearable
      ></el-input>
      <el-input
        v-model="listQuery.phoneNumberB"
        placeholder="请输入手机号"
        class="filter-item"
        clearable
      ></el-input>

      <el-button
        class="filter-item"
        type="primary"
        @click="handleSearch"
        icon="el-icon-search"
        >搜索</el-button
      >

      <!-- <ReadExcel @listenToChildEvent="getExcelData" ref="readExcel"></ReadExcel>

      <el-button
        class="filter-item"
        type="primary"
        @click="handleExport"
        icon="el-icon-plus"
        >导出Excel</el-button
      > -->
      <el-button
        v-if="roles[0] === 8"
        class="filter-item"
        type="primary"
        @click="handlePhase5Export"
        icon="el-icon-download"
        >导出Excel</el-button
      >
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      style="width: 100%; margin-bottom: 20px"
      row-key="id"
      border
    >
      <el-table-column label="房票编号" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.numbering }}</span>
        </template>
      </el-table-column>

      <el-table-column label="用户姓名" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.nameB }}</span>
        </template>
      </el-table-column>

      <el-table-column label="身份证号码" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.idCardB }}</span>
        </template>
      </el-table-column>

      <el-table-column label="手机号" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.phoneNumberB }}</span>
        </template>
      </el-table-column>

      <el-table-column label="状态" align="center" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.currentAccountPhase | currentAccountPhase }}</span>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" align="center" width="100">
        <template slot-scope="scope">
          <span>{{
            scope.row.createDate | parseTime("{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>

      <el-table-column label="处理时间" align="center">
        <template slot-scope="scope">
          <span>{{
            scope.row.phaseDealDate | parseTime("{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        width="300"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            @click="handleProgress(scope.row.id)"
            >工单详情</el-button
          >
          <!-- <el-button
            v-if="
              scope.row.phase === 2 &&
              scope.row.currentAccountPhase === 0 &&
              scope.row.preAudit !== true
            "
            type="primary"
            size="mini"
            @click="handleAudit(scope.row.id, 0)"
            >预审核</el-button
          >
          <el-button
            v-if="
              (scope.row.phase === 2 || scope.row.phase === 3) &&
              scope.row.currentAccountPhase === 0
            "
            type="primary"
            size="mini"
            @click="handleAudit(scope.row.id, 1)"
            >审核通过</el-button
          > -->
          <!-- <el-button
            v-if="scope.row.phase === 3"
            type="primary"
            size="mini"
            @click="handleFourPartyAgreement(scope.row.id)"
            >四方协议</el-button
          > -->
          <!-- <el-button
            type="primary"
            size="mini"
            @click="handleOffShelf(scope.row)"
            >查看协议模板</el-button
          >
          <el-button
            type="primary"
            size="mini"
            @click="handleOffShelf(scope.row)"
            >用户管理</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.current"
      :limit.sync="listQuery.size"
      @pagination="getList"
    />

    <el-dialog
      :title="textMap[dialogStatus] + '项目'"
      :visible.sync="dialogProject"
      @opened="openMethods"
      width="30%"
    >
      <!-- :close-on-click-modal="false"
      :close-on-press-escape="false" -->
      <el-form :model="form" :rules="rules" ref="form" label-width="120px">
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="form.name"></el-input
        ></el-form-item>
        <el-form-item label="项目信息"
          ><el-input v-model="form.detail" type="textarea"></el-input
        ></el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogProject = false">取 消</el-button>
        <el-button type="primary" @click="createAndUpdate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { list } from "@/api/ticket";
import { dealPhase2, phase5Export } from "@/api/housingTicket";
import Pagination from "@/components/Pagination/index";
import { mapGetters } from "vuex";
import { parseTime } from "@/utils";
// import { housingStatusOptions } from "@/utils";
// import ReadExcel from "@/components/ReadExcel";
export default {
  computed: {
    ...mapGetters(["roles"]),
  },
  components: { Pagination },
  //   computed: {
  //     statusCmp() {
  //       return (status) => {
  //         return housingStatusOptions.find((item) => item.value === status).label;
  //       };
  //     },
  //   },
  filters: {
    phaseFilter(phase) {
      const phaseMap = {
        0: "房票签约阶段",
        1: "选房阶段",
        2: "贷款审查阶段",
        3: "签订四方协议阶段",
        4: "登记备案阶段",
        5: "结算确认阶段",
        6: "还款阶段",
        7: "完结",
      };
      return phaseMap[phase];
    },
    currentAccountPhase(status) {
      const statusMap = {
        0: "待处理",
        1: "已处理",
        null: "全部",
      };
      return statusMap[status];
    },
  },
  data() {
    return {
      total: 0,
      list: [],
      listQuery: {
        current: 1,
        size: 10,
        currentAccountPhase: 1,
      },
      listLoading: false,
      //   housingStatusOptions,
      downloadLoading: false,
      dialogProject: false,
      form: {},
      textMap: {
        update: "修改",
        create: "创建",
      },
      dialogStatus: "",
      rules: {
        name: { required: true, message: "不能为空", trigger: "blur" },
        // detail: { required: true, message: "不能为空", trigger: "blur" },
      },
    };
  },
  created() {
    // this.getBusinessList()
    this.getList();
  },
  methods: {
    openMethods() {
      this.$refs.form.clearValidate();
    },
    getList() {
      list(this.listQuery).then((res) => {
        this.list = res.d.records;
        this.total = res.d.total;
      });
    },
    handleSearch() {
      this.listQuery.current = 1;
      this.getList();
    },
    handleCreate() {
      //   this.$nextTick(() => {}, 100);
      //   this.form = {};
      //   this.dialogStatus = "create";
      //   this.dialogProject = true;
      this.$router.push({
        path: "/ticket/create",
      });
    },
    createAndUpdate() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          createAndUpdate(this.form).then((res) => {
            if (res.c === 200) {
              this.$message.success(`${this.textMap[this.dialogStatus]}成功`);
              this.getList();
              this.dialogProject = false;
            }
          });
        }
      });
    },
    handerDetail(row) {
      const { id, type } = row;
      this.$router.push({
        path: "/housing/detail",
        query: { id, type },
      });
    },
    handleOffShelf(row) {
      let payload = {
        id: row.id,
        status: row.status === "SALE" ? "OFF_SHELF" : "SALE",
      };
      offShelf(payload).then((res) => {
        if (res.c === 200) {
          this.$message.success(
            (payload.status === "SALE" ? "上架" : "下架") + "成功"
          );
        }
        this.getList();
      });
    },
    // 修改(提交)
    confirm({ data, close, hideLoading }) {
      update(data)
        .then((res) => {
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs["table"].getList();
          close();
        })
        .catch(() => {
          hideLoading();
        });
    },
    // 修改(表单显示)
    // handleUpdate(id) {
    //   this.$router.push({ path: "fourPartyAgreement", query: { id } });
    // },
    // 重置密码
    handleResetPsw(row) {
      const { id } = row;
      this.$prompt("请输入新密码", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputValidator: (value) => {
          if (!value) return "请输入新密码";
          if (value.length < 6) return "请输入6位以上密码";
          return true;
        },
        inputErrorMessage: "密码不正确",
      }).then(({ value }) => {
        reset({
          id,
          password: value,
        }).then((res) => {
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
      });
    },
    // 删除
    handerDel(row) {
      const { name, id } = row;
      this.$confirm(`是否删除${name}?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteInfo({ id }).then((res) => {
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs["table"].getList();
        });
      });
    },
    handleAudit(id, type) {
      dealPhase2({
        id,
        type,
      }).then((res) => {
        console.log(res);
        this.$message.success(`${type === 0 && "预"}审核成功`);
      });
    },
    getExcelData(data) {
      console.log(data);
    },
    handlePhase5Export() {
      this.downloadLoading = true;
      import("@/vendor/Export2Excel").then((excel) => {
        const tHeader = [
          "日期",
          "用户姓名",
          "首套/二套",
          "身份证号码",
          "房号",
          "车位号",
          "购房总额",
          "监管金额",
          "补偿金额",
          "贷款总额",
          "期数",
          "每月应还",
          "实际每月应还",
          "购房款首付",
          "应退还补偿",
          "服务费(0.03)",
          "联系电话",
          "还款银行卡号",
          "还款开户行",
          "退款银行卡号",
          "退款开户行",
          "退款银行卡姓名",
        ];
        const filterVal = [
          "createDate",
          "nameB",
          "roomType",
          "idCardB",
          "homeInfo",
          "carInfo",
          "totalPrice",
          "jianguanPrice",
          "number",
          "loanAmount",
          "numberOfInstallments",
          "monthRefund",
          "amountOfInstallments",
          "ticketFirstPay",
          "shouldBeRefunded",
          "serviceCharge",
          "phoneNumberB",
          "repaymentCode",
          "repaymentBank",
          "refundCode",
          "refundBank",
          "refundName",
        ];

        const payload = {
          ...this.listQuery,
          size: 10000,
          current: 1,
        };

        phase5Export(payload).then((response) => {
          excel.export_json_to_excel({
            header: tHeader,
            data: this.formatJsonPhase5(filterVal, response.d),
            filename: "结算确认列表",
          });
        });

        this.downloadLoading = false;
      });
    },
    formatJsonPhase5(filterVal, jsonData) {
      console.log(jsonData);
      return jsonData.map((v) =>
        filterVal.map((j) => {
          if (j === "createDate") {
            return parseTime(v[j]);
          } else if (j === "jianguanPrice") {
            // if(v[totalPrice<number?])
            return v["totalPrice"] < v["number"]
              ? v["totalPrice"]
              : v["number"];
          } else if (j === "repaymentCode") {
            return v["billingInfo"]["repaymentCode"];
          } else if (j === "repaymentBank") {
            return v["billingInfo"]["repaymentBank"];
          } else if (j === "refundCode") {
            return v["billingInfo"]["refundCode"];
          } else if (j === "refundBank") {
            return v["billingInfo"]["refundBank"];
          } else if (j === "refundName") {
            return v["billingInfo"]["refundName"];
          } else {
            return v[j];
          }
        })
      );
    },

    handleProgress(id) {
      this.$router.push({ path: "/ticket/ticketProgress", query: { id } });
    },
  },
};
</script>

<style lang="scss" scoped>
.el-input {
  width: 200px;
  margin-right: 10px;
}
.el-select {
  margin-right: 10px;
}
</style>
