<template>
  <div class="institution">
    <!-- 请选择服务地区 -->
    <div class="area">
      <div class="title">
        <div class="type"><span class="point"></span> 请选择服务地区</div>
      </div>
      <ul class="area_box">
        <li>
          <label>省：</label>
          <a-select
            style="width: 120px"
            @change="handleSelectProvince"
            allowClear
          >
            <a-select-option
              v-for="item in provinceList"
              :key="item.id"
              v-model="item.provinceCode"
              >{{ item.provinceName }}</a-select-option
            >
          </a-select>
        </li>
        <li>
          <label>市：</label>
          <a-select style="width: 120px" @change="handleSelectCity">
            <a-select-option
              v-for="item in cityList"
              :key="item.id"
              v-model="item.cityCode"
              >{{ item.cityName }}</a-select-option
            >
          </a-select>
        </li>
        <li>
          <label>区：</label>
          <a-select style="width: 120px" @change="handleSelectDistrict">
            <a-select-option
              v-for="item in areaList"
              :key="item.id"
              v-model="item.districtCode"
              >{{ item.districtName }}</a-select-option
            >
          </a-select>
        </li>
      </ul>
    </div>
    <!-- 请选择服务机构 -->
    <div class="mechanism">
      <div class="title">
        <div class="type"><span class="point"></span> 请选择服务机构</div>
      </div>
      <div class="mechanism_box">
        <span
          v-for="(item, index) in mechanismList"
          :key="index"
          :class="index === selectIndex ? 'active' : ''"
          @click="clickTab(index, item.id)"
          >{{ item.supplierName }}</span
        >
        <!-- -{{ item.id }} -->
      </div>
    </div>
    <!-- 请选择服务地区 -->
    <div class="hospital">
      <div class="title">
        <div class="type"><span class="point"></span> 请选择服务中心</div>
      </div>
      <ul class="hospital_box" v-if="isShowHospitalList">
        <li v-for="(item, index) in pageData" :key="index">
          <div>
            <p class="top">{{ item.checkUnitName }}</p>
            <p class="bottom">{{ item.address }}</p>
          </div>
          <button
            :class="item.isDisabled ? 'btn disabled' : 'btn'"
            @click="openDatePicker(item)"
          >
            选择服务日期
          </button>
          <!-- -{{ item.supplierId }}-{{ item.id }} -->
        </li>
      </ul>
      <div v-else class="hospital_none">暂无可选分院</div>
      <a-pagination
        style="text-align: right; position: relative; bottom: 10px"
        v-if="hospitalList.length > 5"
        v-model="current"
        :pageSize="5"
        :total="hospitalList.length"
        show-less-items
        @change="pagechange"
      />
    </div>
    <div class="mask" v-if="datePickShow && showDatemask">
      <reserve-date
        ref="reserveDate1"
        :scheduleList="getScheduleList"
        @confirmDate="getConfirm"
        @cancleDate="getCancle"
        @changeDay="
          (date) => {
            return dateChange(date, 0);
          }
        "
        @changeMonth="
          (date) => {
            return changeM(date);
          }
        "
      />
    </div>
  </div>
</template>

<script>
import api from "@/api/customer";
import reserveDate from "../../../components/reserve-date";
import moment from "moment";
export default {
  name: "selectInstitution",
  components: {
    reserveDate,
  },
  props: {
    id: {
      type: String | Number,
      default: "",
    },
  },
  data() {
    return {
      pageData: [],
      current: 1,
      showDatemask: false,
      datePickShow: false,
      selectIndex: 0,
      provinceList: [], //省
      cityList: [], //市
      areaList: [], //区
      provinceCode: "", //选择省
      cityCode: "", //选择市
      areaCode: "", //选择区
      mechanismList: [], //服务机构列表
      hospitalList: [], //服务机构对应下的服务中心列表
      isShowHospitalList: true, //是否显示服务中心列表
      supplierIds: "", //服务中心ids,默认显示全部
      servicepackageId: "", //产品id
      serviceDate: "", //预约的时间
      hospitalId: "", //医院id
      supplierId: "", //选择服务中id
      getScheduleList: [], // 排期列表
      appointmentId: "", // 追加的套餐的id
    };
  },
  created() {
    const { servicepackageId, id } = this.$route.query;
    this.servicepackageId = servicepackageId ? servicepackageId : "";
    this.id = id;
    this.getProvinceList(); //获取省
    this.getSupplierList(); //获取服务机构
    // 获取门店排期
  },

  methods: {
    // 获取门店排期
    getScheduleByCode(beginDate, endDate) {
      const query = {
        code: JSON.stringify(this.hospitalId), //门店编码
        beginDate, //开始时间
        endDate, //结束时间
        supplierId: this.supplierId, //机构id
        chooseList: JSON.parse(window.localStorage.getItem("chooseList")), // 服务
        payList: [], // 付费
        servicepackageId: this.servicepackageId, // 服务包
        customerId: this.id, // 客户id
      };
      api.getScheduleByCode(query).then((res) => {
        if (res.content) {
          this.getScheduleList = res.content;
        }
        this.showDatemask = true;
      });
    },
    // 获取省
    async getProvinceList() {
      const query = {
        chooseList: JSON.parse(window.localStorage.getItem("chooseList")),
        servicepackageId: this.servicepackageId,
      };

      await api.getProvinceList(query).then((res) => {
        if (res.returnCode === "0000") {
          this.provinceList = res.content;
        } else {
          this.$message.error(res.returnMsg);
        }
      });
    },

    changeM(month) {
      // 根据月份查可预约
      this.getScheduleByCode(month.min, month.max);
      console.log("下个月", month);
    },
    // 获取市
    getCityListByProvinceCode() {
      const query = {
        provinceCode: this.provinceCode,
        chooseList: JSON.parse(window.localStorage.getItem("chooseList")),
        servicepackageId: this.servicepackageId,
      };
      api.getCityListByProvinceCode(query).then((res) => {
        if (res.returnCode === "0000") {
          this.cityList = res.content;
        } else {
          this.$message.error(res.returnMsg);
        }
      });
    },

    // 获取区/城市
    getDistrictListByCityCode() {
      const query = {
        cityCode: this.cityCode,
        chooseList: JSON.parse(window.localStorage.getItem("chooseList")),
        servicepackageId: this.servicepackageId,
      };
      api.getDistrictListByCityCode(query).then((res) => {
        if (res.returnCode === "0000") {
          this.areaList = res.content;
        } else {
          this.$message.error(res.returnMsg);
        }
      });
    },

    // 选择省
    handleSelectProvince(value) {
      console.log(`选择省provinceCode= ${value}`);
      this.provinceCode = value || "";
      this.cityCode = "";
      this.areaCode = "";
      this.getCityListByProvinceCode(); // 根据省-获取市
      this.getSupplierList();
    },

    // 选择市
    handleSelectCity(value) {
      console.log(`选择市CityCode= ${value}`);
      this.cityCode = value;
      this.areaCode = "";
      this.getDistrictListByCityCode(); // 根据市-获取区
      this.getSupplierList();
    },

    // 选择区
    handleSelectDistrict(value) {
      this.areaCode = value;
      console.log(`选择区DistrictCode= ${value}`);
      this.getSupplierList();
    },

    // 获取服务机构
    async getSupplierList() {
      // 测试id1043
      api
        .getSupplierList({ servicepackageId: this.servicepackageId })
        .then((res) => {
          if (res.returnCode == "0000") {
            const data = res.content;

            // 提取所有的服务机构ids,并用逗号隔开,比如:1004,1007
            this.supplierIds = data
              .map(function (e, i) {
                return e.id;
              })
              .join(",");

            this.mechanismList = [
              {
                status: "0",
                supplierName: "全部",
                id: this.supplierIds,
              },
              ...res.content,
            ];
            console.log("this.supplierIds===", this.supplierIds);
            this.getShopByDistrictCode(); //根据服务结构-显示可选择的服务中心,默认显示全部
          } else {
            this.$message.error(res.returnMsg);
          }
        });
    },

    // 选择服务机构
    clickTab(index, id) {
      this.selectIndex = index;
      this.supplierIds = id;
      this.current = 1;
      // 点击选择服务机构,显示该机构下的服务中心
      this.getShopByDistrictCode();
    },

    // 根据服务机构-获取服务中心列表
    getShopByDistrictCode() {
      const params = {
        // customerSex: 'M', //性别
        // customerMaritalStatus: '02', //婚姻状况
        chooseList: JSON.parse(window.localStorage.getItem("chooseList")),
        payList: [],
        provinceCode: this.provinceCode, //省编号
        cityCode: this.cityCode, //市编号
        areaCode: this.areaCode, //区号
        supplierIds: this.supplierIds, //服务机构d
        location: ",", //经纬度
        servicepackageId: this.servicepackageId, //产品id
      };
      api.getShopByDistrictCode(params).then((res) => {
        if (res.returnCode === "0000") {
          this.isShowHospitalList = true;
          this.hospitalList = res.content;
          console.log("数量", this.hospitalList);
          console.log("total");
          if (res.content.length > 5) {
            this.pagechange(1, 5);
          } else {
            this.pageData = res.content;
          }
          console.log("根据服务机构-获取服务中心列表=", this.hospitalList);
        } else {
          this.hospitalList = 0;
          this.isShowHospitalList = false;
          // this.$message.error(res.returnMsg)
        }
      });
    },
    // 分页
    pagechange(current, size) {
      var skipNum = (current - 1) * size;
      this.pageData =
        skipNum + size >= this.hospitalList.length
          ? this.hospitalList.slice(skipNum, this.hospitalList.length)
          : this.hospitalList.slice(skipNum, skipNum + size);
    },
    // 打开日期弹框
    openDatePicker(item) {
      if (item.isDisabled) {
        return;
      }
      this.supplierId = item.supplierId;
      this.hospitalId = item.id;
      this.datePickShow = true;

      // 查看排期
      let month = moment().startOf("month").format("yyyyMM");

      let start = month + "01";
      let end = month + moment().daysInMonth();
      this.getScheduleByCode(start, end);
    },

    // 确认选择-"立即预约"
    getConfirm(val) {
      this.datePickShow = false;
      this.showDatemask = false;
      const _this = this;
      const query = {
        dataSource: "M", //数据来源P电脑PC ,M 手机
        customerId: this.id, //客户id
        servicepackageId: this.servicepackageId, //套餐id
        checkUnitCode: JSON.stringify(this.hospitalId), //预约门店code
        serviceDate: this.serviceDate, //预约使用服务时间
        chooseList: JSON.parse(window.localStorage.getItem("chooseList")), //选择服务列表
        payList: [],
        supplierId: this.supplierId, //供应商id
        hospitalId: this.hospitalId, //医院id
      };
      console.log("立即预约=", query);

      // 弹窗-"你预约的日期为:xxxxxx"
      this.$confirm({
        title: "预约时间确认",
        content: `您预约的日期为： ${this.serviceDate}`,
        okText: "确认",
        cancelText: "取消",
        onOk() {
          api.addAppointment(query).then((res) => {
            if (res.returnCode === "0000") {
              _this.$message.success("预约成功");
              _this.appointmentId = res.content;
              // 提示预约成功,之后跳转到预约详情页面
              setTimeout(() => {
                // 需要获取用户id
                _this.$router.push({
                  name: "Detail",
                  query: {
                    id: _this.id,
                    appointmentId: _this.appointmentId,
                  },
                });
              }, 1000);
            } else {
              _this.$message.error(res.returnMsg);
            }
          });
        },
        onCancel() {},
      });
    },

    getCancle(val) {
      this.datePickShow = false;
      this.showDatemask = false;
    },

    dateChange(date, type) {
      console.log(date);
      if (date.length != 0) {
        this.serviceDate = date[0].date;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.mask {
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}
.institution {
  padding: 19.5px 14.5px 33.5px 14.5px;
  background-color: white;
  width: 760px;
  margin: 0 auto;
  font-size: 14px;
  color: #333;
  .title {
    .point {
      display: inline-block;
      border-radius: 5px;
      width: 6px;
      height: 6px;
      background-color: #3f7ffb;
      margin-right: 6px;
      position: relative;
      top: -1px;
    }
    .type {
      font-size: 14px;
      font-weight: bold;
    }
    .item-container {
      margin-top: 8.5px;
    }
  }
  .area_box {
    display: flex;
    justify-content: space-between;
    margin: 25px 0px 45px 0px;
    label {
      color: #aaa;
    }
  }
  .mechanism_box {
    display: flex;
    flex-wrap: wrap;
    margin: 25px 0px 45px 0px;
    align-items: center;
    span {
      display: inline-block;
      height: 42px;
      line-height: 42px;
      padding: 0 38px;
      background: #fafafa;
      border-radius: 4px;
      margin-right: 20px;
    }
    span.active {
      background: #d2d2d2;
    }
  }
  .hospital_box {
    margin: 25px 0px 45px 0px;
    li {
      display: flex;
      height: 98px;
      align-items: center;
      justify-content: space-between;
      background: #fafafa;
      padding: 28px 24px;
      margin-bottom: 12px;
      .top {
        font-size: 14px;
        color: #333;
      }
      .bottom {
        color: #999;
        font-size: 13px;
      }
      .btn {
        outline: none;
        border: none;
        background: linear-gradient(87deg, #ffcb00, #ffb219);
        width: 110px;
        height: 40px;
        border-radius: 4px;
        color: #fff;
      }
      .btn.disabled {
        background: #e2e2e2;
      }
    }
  }
  .hospital_none {
    text-align: center;
    padding: 20px;
  }
}
.ant-btn.ant-btn-primary {
  background: #3f7ffb;
}
</style>
