<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select
        class="filter-item"
        placeholder="请选择类型"
        v-model="listQuery.type"
        clearable
      >
        <el-option label="住房" :value="0"></el-option>
        <el-option label="车位" :value="1"></el-option>
      </el-select>
      <el-input
        v-model="listQuery.building"
        placeholder="请输入楼栋"
        class="filter-item"
        clearable
      ></el-input>

      <el-input
        v-model="listQuery.floor"
        placeholder="请输入楼层"
        class="filter-item"
        clearable
      ></el-input>

      <el-input
        v-model="listQuery.roomNumber"
        placeholder="请输入房号/车位号"
        class="filter-item"
        clearable
      ></el-input>

      <el-input
        v-model="listQuery.houseType"
        placeholder="请输入户型"
        class="filter-item"
        clearable
      ></el-input>

      <el-select
        class="filter-item"
        placeholder="请选择状态"
        v-model="listQuery.status"
        @change="handleStatusChange"
        clearable
      >
        <el-option
          v-for="(item, index) in housingStatusOptions"
          :key="index"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>

      <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
      >

      <el-button
        class="filter-item"
        type="primary"
        @click="handleDownload"
        icon="el-icon-download"
        >下载模板</el-button
      >
      <el-button
        class="filter-item"
        type="primary"
        @click="handleExport"
        icon="el-icon-download"
        >导出Excel</el-button
      >

      <!-- <el-button
        class="filter-item"
        type="primary"
        @click="handleExport"
        icon="el-icon-upload2"
        >房源导入</el-button
      > -->
      <ReadExcel @listenToChildEvent="getExcelData" ref="readExcel"></ReadExcel>
      <!-- <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.propertiesForSaleDeveloperName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="楼盘名称" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.propertiesForSaleName }}</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-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.roomNumber }}</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="面积（㎡）" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.area }}</span>
        </template>
      </el-table-column>

      <el-table-column label="价格" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.price }}</span>
        </template>
      </el-table-column>

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

      <el-table-column
        label="操作"
        align="center"
        width="180"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status === 'OFF_SHELF'"
            type="primary"
            size="mini"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            v-if="scope.row.status !== 'SOLD'"
            type="primary"
            size="mini"
            @click="handleOffShelf(scope.row)"
            >{{ scope.row.status === "SALE" ? "下架" : "上架" }}</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"
    />
  </div>
</template>

<script>
import { housingImport, list, offShelf } from "@/api/housing";
import Pagination from "@/components/Pagination/index";
import { housingStatusOptions } from "@/utils";
import ReadExcel from "@/components/ReadExcel";
import Axios from "axios";
export default {
  components: { Pagination, ReadExcel },
  computed: {
    statusCmp() {
      return (status) => {
        return housingStatusOptions.find((item) => item.value === status).label;
      };
    },
  },
  filters: {
    typeFilter(type) {
      const typeMap = {
        0: "住房",
        1: "车位",
        // 2: "商铺",
      };
      return typeMap[type];
    },
  },
  data() {
    return {
      total: 0,
      list: [],
      listQuery: {
        current: 1,
        size: 10,
      },
      listLoading: false,
      housingStatusOptions,
      downloadLoading: false,
    };
  },
  created() {
    // this.getBusinessList()
    this.getList();
  },
  methods: {
    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.$router.push({
        path: "/housing/create",
      });
    },
    // 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(row) {
      this.$router.push({
        path: "/housing/update",
      });
      localStorage.setItem("housing", JSON.stringify(row));
    },
    handleStatusChange(val) {
      // console.log(val==='');
      if (val === "") {
        this.listQuery.status = undefined;
      }
    },
    getExcelData(data) {
      console.log(data);
      // let arr = []
      // arr = data.flatMap(item=>item)
      // console.log(arr);
      let arr = [];
      data.map((item) => {
        let obj = {
          propertiesForSaleId: item[0], // 楼盘id
          type: item[1] === "住房" ? 0 : 1, //   类型
          building: item[2], //   楼栋
          floor: item[3], //   楼层
          roomNumber: item[4], //   "房号/车位号"
          houseType: item[5], //   户型
          area: item[6], //   "面积（㎡）"
          price: item[7], //   价格
        };
        arr.push(obj);
      });

      housingImport(arr).then((res) => {
        console.log(res);
        if (res.c === 200) {
          this.$message.success("导入房源成功");
          this.getList();
        }
      });
    },
    handleDownload() {
      Axios.get("/static/template.xlsx", {
        //静态资源文件夹public
        responseType: "blob",
      })
        .then((response) => {
          const url = window.URL.createObjectURL(new Blob([response.data]));
          const link = document.createElement("a");
          let fname = "房源模板.xlsx";
          link.href = url;
          link.setAttribute("download", fname);
          document.body.appendChild(link);
          console.log(link);
          link.click();
        })
        .catch((error) => {
          console.log("error:" + JSON.stringify(error));
        });
    },
    handleExport() {
      this.downloadLoading = true;
      import("@/vendor/Export2Excel").then((excel) => {
        const tHeader = [
          "楼盘",
          "类型",
          "楼栋",
          "楼层",
          "房号/车库号",
          "户型",
          "面积",
          "价格",
          "状态",
          "用户类型",
        ];
        const filterVal = [
          "propertiesForSaleName",
          "type",
          "building",
          "floor",
          "roomNumber",
          "houseType",
          "area",
          "price",
          "status",
          "idCard",
        ];

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

        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 === "idCard") {
            let result =
              v["status"] === "SOLD" ? (v[j] ? "安置用户" : "普通用户") : "--";
            return result;
            // 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 if (j === "status") {
            const statusMap = {
              SALE: "在售",
              SOLD: "已售",
              OFF_SHELF: "下架",
            };
            return statusMap[v[j]];
          } else if (j === "type") {
            const typeMap = {
              0: "住房",
              1: "车位",
              2: "商铺",
            };
            return typeMap[v[j]];
          } else {
            return v[j];
          }
        })
      );
    },
    // handleExport() {},
    // // 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>
