<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-select
        v-model="listQuery.currentAccountPhase"
        class="filter-item"
        clearable
        placeholder="请选择状态"
      >
        <el-option label="待处理" :value="0"></el-option>
        <el-option label="已处理" :value="1"></el-option>
        <!-- <el-option label="非本账号阶段" :value="2"></el-option> -->
        <el-option
          v-if="roles === [5]"
          label="银行已预审"
          :value="3"
        ></el-option>
      </el-select>

      <el-button
        class="filter-item"
        type="primary"
        @click="handleSearch"
        icon="el-icon-search"
        >搜索</el-button
      >
      <!-- <el-button
        v-permission="[3]"
        class="filter-item"
        type="primary"
        @click="handleCreate"
        icon="el-icon-plus"
        >新建工单</el-button
      > -->

      <el-button
        v-if="roles[0] === 3"
        class="filter-item"
        type="primary"
        @click="handleExport"
        icon="el-icon-download"
        >导出Excel</el-button
      >

      <el-button
        v-if="roles[0] === 8"
        class="filter-item"
        type="primary"
        @click="handlePhase5Export"
        icon="el-icon-download"
        >导出Excel</el-button
      >

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

      -->
    </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 v-if="roles[0] === 5" label="审核结果" align="center">
        <template slot-scope="scope">
          <span>{{
            scope.row.auditStatus === null
              ? ""
              : scope.row.auditStatus
              ? "通过"
              : "拒绝"
          }}</span>
        </template>
      </el-table-column>

      <el-table-column label="房票金额" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.number }}</span>
        </template>
      </el-table-column>

      <el-table-column label="安置人数" v-if="roles[0] === 3" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.numberOfPlacements }}</span>
        </template>
      </el-table-column>

      <el-table-column label="换房套数" v-if="roles[0] === 3" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.huNumberOfPlacements }}</span>
        </template>
      </el-table-column>

      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <!-- <span>{{ scope.row.currentAccountPhase | currentAccountPhase }}</span> -->
          <el-tag v-if="scope.row.disuse" type="info">已作废</el-tag>
          <el-tag
            v-else-if="scope.row.currentAccountPhase === 0"
            type="warning"
            >{{ scope.row.currentAccountPhase | currentAccountPhase }}</el-tag
          >
          <el-tag
            v-else-if="scope.row.currentAccountPhase === 1"
            type="success"
            >{{ scope.row.currentAccountPhase | currentAccountPhase }}</el-tag
          >
          <span v-else>{{
            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" width="100">
        <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
            v-if="
              roles[0] === 3 &&
              scope.row.currentAccountPhase === 0 &&
              !scope.row.disuse
            "
            type="primary"
            size="mini"
            @click="handleUpdate(scope.row.id)"
            >继续编辑</el-button
          >
          <el-button
            v-if="
              roles[0] === 3 &&
              scope.row.currentAccountPhase !== 0 &&
              scope.row.phase === 0 &&
              !scope.row.disuse
            "
            type="primary"
            size="mini"
            @click="handleUpdate(scope.row.id)"
            >修改协议</el-button
          >
          <el-button
            v-if="scope.row.phase !== 0"
            type="primary"
            size="mini"
            @click="handleDetail(scope.row.id)"
            >工单详情</el-button
          >
          <el-button
            v-if="
              scope.row.waiverOfAgreementFlag !== true &&
              roles[0] === 6 &&
              scope.row.phase === 3 &&
              !scope.row.disuse
            "
            type="primary"
            size="mini"
            @click="handleFourPartyAgreement(scope.row.id)"
            >编辑协议</el-button
          >
          <!-- @click="$router.push({ path: '/fqcnsDetail', query })" -->
          <el-button
            v-if="scope.row.waiverOfAgreementFlag === true"
            type="primary"
            size="mini"
            @click="
              $router.push({
                path: '/fqcnsDetail',
                query: { id:scope.row.id },
              })
            "
            >填写自愿放弃协议</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>

    <el-dialog
      title="分期信息填写"
      :visible.sync="dialogAudit"
      @opened="openMethods"
      width="30%"
    >
      <el-form
        :model="auditForm"
        :rules="rules"
        ref="auditForm"
        label-width="120px"
      >
        <el-form-item
          label="每期还款金额"
          prop="repaymentPlan.amountOfInstallments"
        >
          <el-input v-model="auditForm.repaymentPlan.amountOfInstallments" />
        </el-form-item>
        <el-form-item label="分期数" prop="repaymentPlan.numberOfInstallments">
          <el-input v-model="auditForm.repaymentPlan.numberOfInstallments" />
        </el-form-item>
        <el-form-item label="首次还款期限" prop="repaymentPlan.startDate">
          <el-date-picker
            v-model="auditForm.repaymentPlan.startDate"
            type="datetime"
            value-format="timestamp"
            placeholder="选择日期时间"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogAudit = false">取 消</el-button>
        <el-button type="primary" @click="audit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { list, listExport } from "@/api/ticket";
import { dealPhase2, dealPhase4, 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: "已处理",
        // 2: "非本账号阶段",
        3: "银行已预审",
      };
      return statusMap[status];
    },
  },
  data() {
    return {
      total: 0,
      list: [],
      listQuery: {
        current: 1,
        size: 10,
      },
      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" },
      },
      auditForm: {
        id: undefined,
        repaymentPlan: {
          amountOfInstallments: undefined,
          numberOfInstallments: undefined,
          startDate: undefined,
        },
        type: 0,
      },
      dialogAudit: false,
    };
  },
  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();
    //   });
    // },

    // 修改(表单显示)
    handleUpdate(id) {
      this.$router.push({ path: "detail", query: { id } });
    },

    handleAudit(id, type) {
      if (type === 1) {
        this.dialogAudit = true;
      } else {
        this.resetForm();
        this.form.id = id;
        this.form.type = type;
        this.$confirm(`是否确认?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          dealPhase2({ id, type }).then((res) => {
            if (res.c === 200) {
              this.$message.success("操作成功");
              this.getList();
            }
          });
        });
      }
    },
    getExcelData(data) {
      console.log(data);
    },
    handleExport() {
      this.downloadLoading = true;
      import("@/vendor/Export2Excel").then((excel) => {
        const tHeader = [
          "房票协议编号",
          "用户姓名",
          "身份证号码",
          "手机号",
          "房票金额",
          "安置人数",
          "换房套数",
          "安置用户",
        ];
        const filterVal = [
          "numbering",
          "nameB",
          "idCardB",
          "phoneNumberB",
          "number",
          "numberOfPlacements",
          "huNumberOfPlacements",
          "placementsData",
        ];

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

        listExport(payload).then((response) => {
          excel.export_json_to_excel({
            header: tHeader,
            data: this.formatJson(filterVal, response.d),
            filename: "工单列表",
          });
        });

        this.downloadLoading = false;
      });
    },

    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          if (j === "phase") {
            const map = {
              0: "房票签约阶段",
              1: "选房阶段",
              2: "贷款审查阶段",
              3: "签订四方协议阶段",
              4: "登记备案阶段",
              5: "结算确认阶段",
              6: "还款阶段",
              7: "完结",
            };
            return map[v[j]];
            // return this.housingStatusOptions.find((item) => item.value === v[j])
            //   .label;
          } else {
            return v[j];
          }
        })
      );
    },
    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];
          }
        })
      );
    },

    handleFourPartyAgreement(id) {
      this.$router.push({ path: "fourPartyAgreementCreate", query: { id } });
    },
    handleDetail(id) {
      this.$router.push({ path: "ticketProgress", query: { id } });
    },
    // handerParent(row) {
    // businessInfoId
    // console.log(this.tableProps.filterFields);
    // this.tableProps.filterFields.push({
    //   prop: "businessInfoId",
    // });

    // this.tableProps.fields.secondaryType.props.disabled = true
    // },

    // phase4 登记备案
    handleRegistries(id) {
      dealPhase4({ id }).then((res) => {
        if (res.c === 200) {
          this.$message.success("登记备案成功");
          this.getList();
        }
      });
    },
    handleUpdateFourAspect(id) {
      this.$router.push({
        path: "/ticket/fourPartyAgreementDetail",
        query: { id },
      });
    },
    audit() {
      let payload = JSON.parse(JSON.stringify(this.auditForm));
      payload.repaymentPlan.startDate = payload.repaymentPlan.startDate / 1000;
      dealPhase2(payload).then((res) => {
        if (res.c === 200) {
          this.$message.success(`审核成功`);
          this.dialogAudit = false;
          this.getList();
        }
      });
    },
  },
};
</script>

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