<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.name"
        placeholder="请输入项目名称"
        class="filter-item"
        clearable
      ></el-input>

      <el-button
        class="filter-item"
        type="primary"
        @click="handleSearch"
        icon="el-icon-search"
        >搜索</el-button
      >
      <el-button
        class="filter-item"
        type="primary"
        @click="handleCreate"
        icon="el-icon-plus"
        >新建项目</el-button
      >

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

      <el-button
        class="filter-item"
        type="primary"
        @click="handleExport"
        icon="el-icon-plus"
        >导出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.name }}</span>
        </template>
      </el-table-column>

      <el-table-column label="项目信息" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.detail }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="货币化安置总面积（m²）"
        align="center"
        width="110"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.totalAreaOfMonetizedPlacement }}</span>
        </template>
      </el-table-column>

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

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

      <el-table-column label="总安置人数" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.totalNumberOfPlacements }}</span>
        </template>
      </el-table-column>

      <el-table-column label="已购房票数" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.numberOfTicketsPurchased }}</span>
        </template>
      </el-table-column>

      <el-table-column label="已购房票面积" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.purchasedTicketArea }}</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="handleUpdate(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="primary"
            size="mini"
            @click="handleCheckTemplate(scope.row)"
            >查看协议模板</el-button
          >
          <el-button
            type="primary"
            size="mini"
            @click="handleUserList(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>
  </div>
</template>

<script>
import { list, createAndUpdate } from "@/api/project";
import Pagination from "@/components/Pagination/index";
// import { housingStatusOptions } from "@/utils";
// import ReadExcel from "@/components/ReadExcel";
export default {
  components: { Pagination },
  //   computed: {
  //     statusCmp() {
  //       return (status) => {
  //         return housingStatusOptions.find((item) => item.value === status).label;
  //       };
  //     },
  //   },
  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" },
      },
    };
  },
  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: "/housing/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(row) {
      this.form = Object.assign({}, row);
      this.dialogStatus = "update";
      this.dialogProject = true;
    },
    // 重置密码
    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();
        });
      });
    },
    // 强制登录
    async handerLogin(row) {
      const { type } = row;
      const { d: token } = await forceLogin({
        forceLogin: true,
        // staffType: row.type,
        secondaryType: row.secondaryType,
        username: row.username,
        password: "123456",
      });
      if (type === "SYSTEM") {
        setToken(token);
        location.reload();
        return;
      }
      const { d: userInfo } = await forceLoginInfo({ id: row.id });
      console.log(token);
      console.log(userInfo);
      sessionStorage.setItem("token", token);
      sessionStorage.setItem("userInfo", JSON.stringify(userInfo));
      sessionStorage.setItem("platform", "BUSINESS");
      sessionStorage.setItem(
        "roles",
        JSON.stringify([row.type, row.secondaryType])
      );
      switch (row.secondaryType) {
        case "EMPLOYER":
          // location.href = location.origin + '/employerServices'
          window.open(location.origin + "/employerServices");
          break;
        case "ACADEMIC_EDUCATION":
        case "NON_ACADEMIC_EDUCATION":
          window.open(location.origin + "/educationalServices");
          // location.href = location.origin + '/educationalServices'
          break;
      }
    },
    getExcelData(data) {
      console.log(data);
    },
    handleExport() {
      this.downloadLoading = true;
      import("@/vendor/Export2Excel").then((excel) => {
        const tHeader = [
          "楼盘名称",
          "楼栋",
          "面积（㎡）",
          "户型",
          "楼层",
          "房号",
          "价格",
          "房屋情况介绍",
          "状态",
        ];
        const filterVal = [
          "propertiesForSaleDeveloperName",
          "building",
          "area",
          "houseType",
          "floor",
          "roomNumber",
          "price",
          "detail",
          "status",
        ];

        const payload = {
          size: 10000,
          current: 1,
          extra: {},
        };

        list(payload).then((response) => {
          excel.export_json_to_excel({
            header: tHeader,
            data: this.formatJson(filterVal, response.d.records),
            filename: "房源列表",
          });
        });

        this.downloadLoading = false;
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          //   if (j === "status") {
          //     return this.housingStatusOptions.find((item) => item.value === v[j])
          //       .label;
          //   } else {
          return v[j];
          //   }
        })
      );
    },
    // handerParent(row) {
    // businessInfoId
    // console.log(this.tableProps.filterFields);
    // this.tableProps.filterFields.push({
    //   prop: "businessInfoId",
    // });

    // this.tableProps.fields.secondaryType.props.disabled = true
    // },
    handleCheckTemplate() {
      this.$router.push("previewAgreementTemplate");
    },
    handleUserList(id) {
      this.$router.push({ path: "ticketUserList", query: { id } });
    },
  },
};
</script>

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