<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select
        placeholder="请选择楼盘"
        class="filter-item"
        v-model="listQuery.propertiesForSaleId"
        clearable
        filterable
      >
        <el-option
          v-for="item in buildingOptions"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        ></el-option>
      </el-select>

      <el-select
        class="filter-item"
        v-model="listQuery.type"
        clearable
        placeholder="请选择类型"
      >
        <el-option label="住房" value="0"></el-option>
        <el-option label="车位" value="1"></el-option>
        <!-- <el-option label="商铺" value="2"></el-option> -->
      </el-select>

      <el-input
        v-model="listQuery.roomNumber"
        placeholder="请输入房号"
        class="filter-item"
        clearable
      ></el-input>
      <el-input
        v-model="listQuery.building"
        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"
        v-model="listQuery.status"
        clearable
        @change="handleStatusChange"
      >
        <el-option label="在售" value="SALE"></el-option>
        <el-option label="已售" value="SOLD"></el-option>
        <!-- <el-option label="下架" value="OFF_SHELF"></el-option> -->
      </el-select>
      <el-checkbox v-model="listQuery.cross" style="margin-right: 10px"
        >跨楼盘</el-checkbox
      >

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

      <el-button
        class="filter-item"
        type="primary"
        @click="handleSold"
        :disabled="!multipleSelection.length > 0"
        icon="el-icon-download"
        >售房处理</el-button
      >

      <el-button
        class="filter-item"
        type="primary"
        @click="handleExport"
        icon="el-icon-download"
        >导出Excel</el-button
      >
    </div>
    <el-table
      v-loading="listLoading"
      ref="table"
      @selection-change="handleSelectionChange"
      :data="list"
      style="width: 100%; margin-bottom: 20px"
      :row-key="getRowKeys"
      border
    >
      <el-table-column
        :reserve-selection="true"
        type="selection"
        width="55"
        :selectable="selectable"
      ></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>{{ scope.row.status | statusFilter }}</span>
        </template>
      </el-table-column>

      <el-table-column label="用户类型" align="center">
        <template slot-scope="scope">
          <span>{{
            scope.row.status === "SOLD"
              ? scope.row.idCard
                ? "安置用户"
                : "普通用户"
              : "--"
          }}</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="scope.row.status == 'SALE'"
            type="primary"
            size="mini"
            @click="handleBind(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="售房处理"
      :visible.sync="dialogBind"
      width="40%"
      :close-on-click-modal="false"
    >
      <!-- <div style="margin-left: 50px">房票编号：<el-input ></el-input></div> -->
      <el-form :model="form" :rules="rules" ref="form" label-width="120px">
        <el-form-item label="用户类型：">
          <el-radio-group
            v-model="customerType"
            @change="handleCustomerTypeChange"
          >
            <el-radio :label="0">安置用户</el-radio>
            <el-radio :label="1">普通用户</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="房票编号：">
          <el-input v-model="ticketNumber"></el-input>
          <el-button
            type="primary"
            size="mini"
            @click="getUserListByTicketNumber()"
            >搜索</el-button
          >
        </el-form-item>

        <div v-if="isCar" style="color: red">
          <el-form-item>
            安置用户：安置用户车位无法单独销售，请与住房绑定销售。
          </el-form-item>
        </div>

        <div v-else>
          <div v-if="customerType === 0">
            <div v-for="(ite, idx) in this.form.payload" :key="idx">
              <div v-for="(item, index) in ite.jiaFContents" :key="index">
                <el-form-item v-if="ite.jiaFContents.length > 1">
                  <el-button
                    type="danger"
                    @click="removeJiaF(idx, index)"
                    size="small"
                    >删除</el-button
                  >
                </el-form-item>
                <el-form-item label="姓名：">
                  <!-- <el-input v-model="item.name"></el-input> -->
                  <el-select
                    v-model="item.name"
                    @change="handleNameChange(item.name, idx, index)"
                  >
                    <el-option
                      v-for="opt in tnUserOptions"
                      :key="opt.idCard"
                      :value="opt.name"
                      >{{ opt.name }}</el-option
                    >
                  </el-select>
                </el-form-item>
                <el-form-item label="身份证号：">
                  <el-input v-model="item.idCard"></el-input>
                </el-form-item>
                <el-form-item label="地址：">
                  <el-input v-model="item.address"></el-input>
                </el-form-item>
                <el-form-item label="电话：">
                  <el-input v-model="item.phoneNumber"></el-input>
                </el-form-item>
              </div>
              <el-form-item>
                <el-button type="primary" @click="addJiaF(idx)" size="small"
                  >新增甲方</el-button
                >
              </el-form-item>
              <!-- <el-form-item label="房票总金额：" v-if="form.payload.length > 1">
              </el-form-item> -->
              <el-form-item label="分配金额：" v-if="form.payload.length > 1">
                <el-input v-model="ite.number"></el-input
                ><span
                  >房票总金额：<el-button
                    v-if="!ticketPrice"
                    type="primary"
                    size="mini"
                    @click="getPhase1GetTicketNumber"
                    >查询</el-button
                  ><span v-else>{{ ticketPrice }}</span></span
                >
              </el-form-item>
              <el-form-item label="房号" v-if="multipleSelection[idx]">
                <!-- {{houseInfo[idx].propertiesForSaleName+houseInfo[idx].propertiesForSaleDetail}} -->
                {{
                  multipleSelection &&
                  multipleSelection[idx].roomNumber
                  
                }}
                <!-- {{multipleSelection[idx]}} -->
              </el-form-item>
              <el-form-item label="购房价格："
                ><el-input
                  v-model="form.payload[idx].housingResourcesDataS[0].salePrice"
                  @blur="
                    priceChange(
                      idx,
                      form.payload[idx].housingResourcesDataS[0].salePrice
                    )
                  "
                ></el-input
              ></el-form-item>

              <el-form-item label="首套/二套：">
                <!-- <el-input v-model="form.payload[idx].roomType"></el-input> -->
                <el-radio v-model="form.payload[idx].roomType" label="首套"
                  >首套</el-radio
                >
                <el-radio v-model="form.payload[idx].roomType" label="二套"
                  >二套</el-radio
                >
              </el-form-item>
              <el-form-item label="是否购买车位：">
                <el-radio-group
                  v-model="form.payload[idx].hasCar"
                  @change="(val) => handleRadioCarChange(val, idx)"
                >
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
              <div v-if="form.payload[idx].hasCar">
                <el-form-item label="车位信息：">
                  <div style="display: flex">
                    <el-select
                      placeholder="请选择"
                      v-model="form.payload[idx].carInfo.id"
                      @change="(val) => handleCarChange(val, idx)"
                    >
                      <!-- @change="handleCarChange" -->
                      <!-- (...arr) => checkManager(field.name, ...arr) -->
                      <el-option
                        v-for="item in carOptions"
                        :key="item.id"
                        :label="item.building + item.roomNumber"
                        :value="item.id"
                      ></el-option>
                    </el-select>
                  </div>
                </el-form-item>
                <el-form-item label="车位价格："
                  ><el-input
                    v-model="
                      form.payload[idx].housingResourcesDataS[1].salePrice
                    "
                    @blur="
                      priceChange(
                        idx,
                        form.payload[idx].housingResourcesDataS[1].salePrice
                      )
                    "
                  ></el-input
                  >元</el-form-item
                >

                <el-form-item label="购房总价："
                  >{{ form.payload[idx].totalPrice }}元</el-form-item
                >
              </div>
              <hr />
            </div>
          </div>
          <div v-else>
            <el-form-item label="是否购买车位：">
              <el-radio-group
                v-model="form.payload[0].hasCar"
                @change="(val) => handleRadioCarChange(val, 0)"
              >
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <div v-if="form.payload[0].hasCar">
              <el-form-item label="车位信息：">
                <div style="display: flex">
                  <el-select
                    placeholder="请选择"
                    v-model="form.payload[0].carInfo.id"
                    @change="(val) => handleCarChange(val, 0)"
                  >
                    <el-option
                      v-for="item in carOptions"
                      :key="item.id"
                      :label="item.building + item.roomNumber"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </div>
              </el-form-item>
              <el-form-item label="车位价格："
                ><el-input
                  v-model="form.payload[0].housingResourcesDataS[1].salePrice"
                  @blur="
                    priceChange(
                      0,
                      form.payload[0].housingResourcesDataS[1].salePrice
                    )
                  "
                ></el-input
                >元</el-form-item
              >

              <el-form-item label="购房总价："
                >{{ form.payload[0].totalPrice }}元</el-form-item
              >
            </div>
          </div>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogBind = false">取 消</el-button>
        <!-- :disabled="isCar || !customerType === 0" -->
        <el-button type="primary" @click="submitData">确 定</el-button>
        <!-- :disabled="isCar && customerType === 0" -->
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { list, deal, phase1GetTicketNumber } from "@/api/housingTicket";
import { list as buildingList } from "@/api/building";
import Pagination from "@/components/Pagination/index";
import NP from "number-precision";
import { ticketNumberforUserList } from "@/api/kfs";
export default {
  components: { Pagination },
  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,
      downloadLoading: false,
      dialogBind: false,

      textMap: {
        update: "修改",
        create: "创建",
      },
      dialogStatus: "",
      rules: {
        // nameB: { required: true, message: "不能为空", trigger: "blur" },
        // idCardB: { required: true, message: "不能为空", trigger: "blur" },
        "jiaFContents.name": {
          required: true,
          message: "不能为空",
          trigger: "blur",
        },
      },
      multipleSelection: [],
      carOptions: [],
      customerType: 0,
      hasCar: [],
      carId: undefined,
      houseInfo: [],
      carInfo: {},
      totalPrice: [],
      ticketNumber: undefined,
      tnUserOptions: [],
      // form: {
      //   housingResourcesDataS: [
      //     {
      //       id: "",
      //       salePrice: 0,
      //     },
      //   ],
      //   jiaFContents: [
      //     {
      //       name: undefined,
      //       idCard: undefined,
      //       address: undefined,
      //       phoneNumber: undefined,
      //     },
      //   ],
      // },
      form: {
        payload: [
          {
            housingResourcesDataS: [
              {
                id: "",
                salePrice: 0,
              },
              {
                id: "",
                salePrice: 0,
              },
            ],
            idCardB: "",
            jiaFContents: [
              {
                address: "",
                idCard: "",
                name: "",
                phoneNumber: "",
              },
            ],
            nameB: "",
            number: 0,
          },
        ],
      },
      ticketPrice: undefined,

      buildingOptions: [],
      isCar: false,
      jiaFContents: [
        {
          name: undefined,
          idCard: undefined,
          address: undefined,
          phoneNumber: undefined,
        },
      ],
      multipleSelection: [],
    };
  },
  created() {
    this.getList();
    this.getBuildings();
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    selectable(row, index) {
      if (row.status == "SOLD" || row.type === 1) {
        return false;
      } else {
        return true;
      }
    },
    getRowKeys(row) {
      return row.id;
    },
    submitData() {
      if (this.multipleSelection > 1) {
        let sumNumber = 0;
        if (this.ticketPrice) {
          this.form.payload.map((item) => {
            sumNumber += Number(item.number);
          });
          if (sumNumber === this.ticketPrice) {
            let payload = JSON.parse(JSON.stringify(this.form.payload));
            console.log(payload);
            payload.map((item) => {
              if (!item.housingResourcesDataS[1]) {
                item.housingResourcesDataS.splice(1, 1);
              }
            });
            deal(payload).then((res) => {
              if (res.c === 200) {
                this.$message.success("处理成功");
                this.dialogBind = false;
                this.multipleSelection = [];
                this.$refs.table.clearSelection();
                this.getList();
              }
            });
          } else {
            this.$message.error("请检查分配金额是否等于房票总金额");
          }
        } else {
          this.$message.error("请查询房票总金额,并填写分配金额");
        }
      } else {
        let payload = JSON.parse(JSON.stringify(this.form.payload));
        console.log(payload);
        payload.map((item) => {
          if (!item.housingResourcesDataS[1]) {
            item.housingResourcesDataS.splice(1, 1);
          }
        });
        deal(payload).then((res) => {
          if (res.c === 200) {
            this.$message.success("处理成功");
            this.dialogBind = false;
            this.multipleSelection = [];
            this.$refs.table.clearSelection();
            this.getList();
          }
        });
      }
    },
    getList() {
      list(this.listQuery).then((res) => {
        this.list = res.d.records;
        this.total = res.d.total;
      });
    },
    getCarList() {
      list({ current: 1, size: 99999, type: 1, status: "SALE" }).then((res) => {
        this.carOptions = res.d.records;
      });
    },
    getBuildings() {
      buildingList({ current: 1, size: 99999 }).then((res) => {
        this.buildingOptions = res.d.records;
      });
    },
    handleSearch() {
      this.listQuery.current = 1;
      this.getList();
    },
    resetForm() {
      this.houseInfo = [];
      this.carInfo = {};
      this.hasCar = 0;
      this.carId = undefined;
    },

    // handleCarChange(val) {
    //   this.carOptions.map((item) => {
    //     if (item.id === val) {
    //       this.carInfo = item;
    //     }
    //   });
    //   this.totalPrice = NP.plus(this.carInfo.price, this.houseInfo.price);

    //   this.form.housingResourcesDataS[1] = {
    //     id: this.carInfo.id,
    //     salePrice: this.carInfo.price,
    //   };
    // },
    handleCarChange(val, idx) {
      this.carOptions.map((item) => {
        if (item.id === val) {
          this.form.payload[idx].carInfo = item;
          this.$set(this.form.payload[idx].housingResourcesDataS, 1, {
            id: item.id,
            salePrice: item.price,
          });
          this.priceChange(
            idx,
            this.form.payload[idx].housingResourcesDataS[1].salePrice
          );
        }
      });
    },
    handleRadioCarChange(val, idx) {
      this.form.payload[idx].hasCar = val;
      this.form.payload[idx].carInfo = {};
      this.$set(this.form.payload[idx].housingResourcesDataS, 1, {
        id: undefined,
        salePrice: undefined,
      });
      this.priceChange(idx);
    },
    handleStatusChange(val) {
      if (!val) {
        this.listQuery.status = undefined;
      }
    },
    priceChange(idx, price) {
      this.form.payload[idx].totalPrice =
        Number(this.form.payload[idx].housingResourcesDataS[0].salePrice) +
        (this.form.payload[idx].housingResourcesDataS[1].salePrice
          ? Number(this.form.payload[idx].housingResourcesDataS[1].salePrice)
          : 0);
    },
    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 = {
          size: 10000,
          current: 1,
          extra: {},
          projectId: this.listQuery.projectId,
          ...this.listQuery,
        };

        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];
          }
        })
      );
    },
    addJiaF(idx) {
      this.form.payload[idx].jiaFContents.push({
        name: undefined,
        idCard: undefined,
        address: undefined,
        phoneNumber: undefined,
      });
    },
    removeJiaF(idx, index) {
      this.form.payload[idx].jiaFContents.splice(index, 1);
    },
    validateIdCard(idCard) {
      const idCardPattern =
        /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;

      if (!idCardPattern.test(idCard)) {
        this.$message.error("身份证号格式不正确");
      } else {
        //
      }
    },
    handleSold() {
      this.customerType = 0;
      this.dialogBind = true;
      this.form.payload = [];
      this.multipleSelection.map((item) => {
        this.form.payload.push({
          housingResourcesDataS: [
            {
              id: item.id,
              salePrice: item.price,
            },
            {
              id: undefined,
              salePrice: undefined,
            },
          ],
          idCardB: "",
          number: "",
          jiaFContents: [
            {
              name: undefined,
              idCard: undefined,
              address: undefined,
              phoneNumber: undefined,
            },
          ],
          hasCar: 0,
          carInfo: {},
          totalPrice: 0,
        });
        this.houseInfo.push(item);
      });
      // this.form.housingResourcesDataS=[]
      // this.isCar = this.houseInfo.type ? true : false;
      // this.form.housingResourcesDataS.push({
      //   id: this.houseInfo.id,
      //   salePrice: this.houseInfo.price,
      // });
      this.getCarList();
      // localStorage.setItem(
      //   "housingSoldInfo",
      //   JSON.stringify(this.multipleSelection)
      // );
      // this.$router.push("housingSoldInfo");
    },
    getPhase1GetTicketNumber() {
      // phase1GetTicketNumber(this.form.payload).then((res) => {
      //   console.log(res);
      //   this.ticketPrice = res.d;
      // });
      ticketNumberforUserList({ numbering: this.ticketNumber }).then((res) => {
        // console.log(res);
        this.ticketPrice = res.d.number;
      });
    },
    handleCustomerTypeChange(val) {
      console.log(val);
      this.form.payload = [];

      this.multipleSelection.map((item, index) => {
        this.form.payload.push({
          housingResourcesDataS: [
            {
              id: item.id,
              salePrice: item.price,
            },
            {
              id: undefined,
              salePrice: undefined,
            },
          ],
          idCardB: "",
          number: "",
          jiaFContents:
            val === 1
              ? null
              : [
                  {
                    name: undefined,
                    idCard: undefined,
                    address: undefined,
                    phoneNumber: undefined,
                  },
                ],
          hasCar: 0,
          carInfo: {},
          totalPrice: 0,
        });
        this.houseInfo.push(item);
      });
    },
    getUserListByTicketNumber() {
      ticketNumberforUserList({ numbering: this.ticketNumber }).then((res) => {
        console.log(res);
        this.tnUserOptions = res.d.userList;
      });
    },
    handleNameChange(name, idx, index) {
      console.log(name, this.tnUserOptions, index);
      let obj = this.tnUserOptions.find((item) => item.name === name);
      this.form.payload[idx].jiaFContents[index].idCard = obj.idCard;
    },
  },
};
</script>

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