<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="handleBind"
        >绑定</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"
      @selection-change="handleSelectionChange"
      row-key="id"
      border
    >
      <el-table-column type="selection" width="55" :selectable="selectable">
      </el-table-column>
      <el-table-column label="楼栋" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.building }}</span>
        </template>
      </el-table-column>

      <el-table-column label="楼层" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.floor }}</span>
        </template>
      </el-table-column>

      <el-table-column label="户型" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.houseType }}</span>
        </template>
      </el-table-column>

      <el-table-column label="楼盘id" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.propertiesForSaleId }}</span>
        </template>
      </el-table-column>

      <el-table-column label="楼盘开发商名称" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.propertiesForSaleDeveloperName }}</span>
        </template>
      </el-table-column>

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

      <el-table-column label="类型" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.type | typeFilter }}</span>
        </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="售房处理"
      :visible.sync="dialogBind"
      @opened="openMethods"
      width="30%"
    >
      <el-form :model="form" :rules="rules" ref="form" label-width="120px">
        <el-form-item label="用户类型：">
          <el-radio-group v-model="radio">
            <el-radio :label="0">安置用户</el-radio>
            <el-radio :label="1">普通用户</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="姓名：" prop="nameB"
          ><el-input v-model="form.nameB" type="textarea"></el-input
        ></el-form-item>
        <el-form-item label="手机号：" prop="nameB"
          ><el-input v-model="form.nameB" type="textarea"></el-input
        ></el-form-item>
        <!-- <el-form-item>
          已选楼盘数：{{ multipleSelection.length }}
        </el-form-item> -->
        <el-form-item label="身份证号：" prop="idCardB">
          <el-input v-model="form.idCardB"></el-input
        ></el-form-item>
        <el-form-item label="是否购买车位：">
          <el-radio-group v-model="radio">
            <el-radio :label="0">是</el-radio>
            <el-radio :label="1">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item label="姓名：" prop="nameB"
          ><el-input v-model="form.nameB" type="textarea"></el-input
        ></el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogBind = false">取 消</el-button>
        <el-button type="primary" @click="submitData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { list, deal } from "@/api/housingTicket";
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;
  //       };
  //     },
  //   },
  filters: {
    typeFilter(type) {
      const typeMap = {
        0: "住房",
        1: "车位",
        2: "商铺",
      };
      return typeMap[type];
    },
    statusFilter(status) {
      const statusMap = {
        SALE: "在售",
        SOLD: "已售",
        OFF_SHELF: "下架",
      };
      return statusMap[status];
    },
  },
  data() {
    return {
      total: 0,
      list: [],
      listQuery: {
        current: 1,
        size: 10,
      },
      listLoading: false,
      //   housingStatusOptions,
      downloadLoading: false,
      dialogBind: false,
      form: {},
      textMap: {
        update: "修改",
        create: "创建",
      },
      dialogStatus: "",
      rules: {
        nameB: { required: true, message: "不能为空", trigger: "blur" },
        idCardB: { required: true, message: "不能为空", trigger: "blur" },
        // detail: { required: true, message: "不能为空", trigger: "blur" },
      },
      multipleSelection: [],
    };
  },
  created() {
    // this.getBusinessList()
    this.getList();
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    selectable(row, index) {
      if (row.status == "SOLD") {
        return false;
      } else {
        return true;
      }
    },
    submitData() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.form.housingResourcesIds = this.multipleSelection.map(
            (item) => item.id
          );
          console.log(this.form);
          deal(this.form).then((res) => {
            if (res.c === 200) {
              this.$message.success("绑定成功");
              this.dialogBind = false;
              this.getList();
            }
          });
        }
      });
    },
    // 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();
    },
    handleBind(row) {
      this.dialogBind = true;
    },
    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.form = Object.assign({}, row);
      // this.dialogStatus = "update";
      // this.dialogProject = true;
      this.$router.push({ path: "detail", 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();
        });
      });
    },
    // 强制登录
    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
    // },
  },
};
</script>

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