<template>
  <div class="fire">
    <div class="safe">
      <div class="content">
        <div class="top">
          <div class="name">{{ detail.name }}</div>
          <van-button
            icon="arrow"
            color="#f77c72"
            round
            icon-position="right"
            size="small"
            @click="jump"
          >
            用户管理
          </van-button>
        </div>
        <div class="user">
          <img class="icon" src="./images/home_icon1.png" alt="" />
          <div class="num">用户号：{{ detail.consNo }}</div>
        </div>
        <div class="add">
          <img class="icon" src="./images/address_icon1.png" alt="" />
          <div class="address">{{ detail.address }}</div>
        </div>
      </div>
      <div class="anjian">
        <div class="title">下次安检时间</div>
        <van-field
          v-model="form.consName"
          required
          readonly
          label="联系人"
          placeholder="请输入联系人"
        />
        <van-field
          v-model="form.mobile"
          type="digit"
          required
          label="联系电话"
          placeholder="请输入联系电话"
        />
        <van-field
          v-model="form.appointDate"
          label="期望日期"
          required
          readonly
          placeholder="请选择期望日期"
          :rules="[{ required: true, message: '请选择期望日期' }]"
          @click="showcurrentDatePicker = true"
        />
        <van-popup v-model="showcurrentDatePicker" position="bottom">
          <van-datetime-picker
            v-model="currentDate"
            type="datehour"
            title="选择期望时间"
            :min-date="minDate"
            :columns-order="['year', 'month', 'day', 'hour']"
            :formatter="formatter"
            @confirm="(value) => oncurrentDateConfirm(value)"
            @cancel="showcurrentDatePicker = false"
          />
        </van-popup>
        <van-field>
          <template #input>
            <div class="tips">提示：具体时间以师傅联系您确定为准</div>
          </template>
        </van-field>
        <van-field
          v-model="form.remark"
          rows="2"
          autosize
          required
          label="故障描述"
          type="textarea"
          maxlength="100"
          placeholder="请填写对上门师傅的备注信息"
          show-word-limit
        />
        <van-field label="户主身份证照片" label-width="200px" required />
        <van-field>
          <template #input>
            <van-uploader
              style="magin-left: 30px"
              v-model="cardFront"
              upload-text="正面"
              max-count="1"
              :after-read="afterRead"
            />
            <van-uploader
              style="magin-left: 30px"
              v-model="cardBack"
              upload-text="背面"
              max-count="1"
              :after-read="afterRead"
            />
          </template>
        </van-field>
        <van-field label="产权证件" required>
          <template #input>
            <van-radio-group v-model="radio" direction="horizontal">
              <van-radio name="1" checked-color="#EB4E3F">房产证</van-radio>
              <van-radio name="2" checked-color="#EB4E3F">购房合同</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field>
          <template #input>
            <van-uploader
              style="magin-left: 30px"
              v-if="radio == '1'"
              v-model="fileList"
              upload-text="房产证"
              max-count="5"
              :after-read="afterRead"
            />
            <van-uploader
              style="magin-left: 30px"
              v-if="radio == '2'"
              v-model="fileList"
              upload-text="购房合同"
              max-count="5"
              :after-read="afterRead"
            />
          </template>
        </van-field>
        <van-field
          label="用气环境(如厨房门窗、燃气热水和燃气灶具等)"
          label-width="100%"
          required
        />
        <van-uploader
          style="magin-left: 30px"
          v-model="fileList1"
          upload-text="用气环境"
          max-count="5"
          :after-read="afterRead"
        />
        <div class="instructions">
          <img
            v-if="act == 1"
            @click="change"
            src="./images/unselect.png"
            alt=""
          />
          <img
            v-if="act == 2"
            @click="change"
            src="./images/select.png"
            alt=""
          />
          我已阅读并同意<span @click="prompt">《用户须知》</span>
        </div>
      </div>
    </div>
    <div class="button">
      <van-button class="operation" @click="submit" size="large" color="#EB4E3F"
        >提交预约</van-button
      >
      <div class="safe-area"></div>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import {
  Button,
  Field,
  Popup,
  DatetimePicker,
  Uploader,
  Dialog,
  Toast,
  RadioGroup,
  Radio,
} from "vant";
import { queryListUser, imageUpload, appointVentilation } from "@/api/rqfy.js";
Vue.use(Button)
  .use(Field)
  .use(Popup)
  .use(DatetimePicker)
  .use(Uploader)
  .use(Dialog)
  .use(Toast)
  .use(RadioGroup)
  .use(Radio);
export default {
  name: "fire",
  data() {
    return {
      detail: {},
      userInfo: {},
      form: {
        consNo: "",
        consName: "",
        mobile: "",
        appointDate: "",
        remark: "",
        fileIdList: [],
        cardBackFileId: "",
        cardFrontFileId: "",
      },
      fileList: [],
      fileList1: [],
      cardFront: [],
      cardBack: [],
      showcurrentDatePicker: false,
      minDate: new Date(),
      currentDate: new Date(), // 期望日期
      act: 1,
      radio: "1",
    };
  },
  watch: {
    radio() {
      this.fileList = [];
    },
  },
  created() {
    if (this.$route.query.type == 5) {
      this.detail = this.$route.query.data;
      this.form.consName = this.detail.name;
    } else {
      if (window.android !== undefined) {
        const res = window.android.getUserInfo(); // 这是一个json字符串
        sessionStorage.setItem("ZJCD-UserInfo", res);
        this.userInfo = JSON.parse(res);
        this.initData();
      } else if (window.webkit) {
        window.webkit &&
          window.webkit.messageHandlers.getUserInfo.postMessage("getUserInfo");
      } else {
        this.$toast("请先登录镇合意app");
      }
      let res = sessionStorage.getItem("ZJCD-UserInfo");
      this.userInfo = JSON.parse(res);
      this.initData();
    }
  },
  methods: {
    // 展示时间格式
    formatter(type, val) {
      if (type === "year") {
        return val + "年";
      }
      if (type === "month") {
        return val + "月";
      }
      if (type === "day") {
        return val + "日";
      }
      if (type === "hour") {
        return val + "时";
      }
      return val;
    },
    // 选择时间
    oncurrentDateConfirm(value) {
      console.log(value);
      this.form.appointDate =
        value.getFullYear() +
        "-" +
        (value.getMonth() + 1 > 9
          ? value.getMonth() + 1
          : "0" + (value.getMonth() + 1)) +
        "-" +
        (value.getDate() > 9 ? value.getDate() : "0" + value.getDate()) +
        " " +
        (value.getHours() > 9 ? value.getHours() : "0" + value.getHours()) +
        ":00:00";
      this.showcurrentDatePicker = false;
    },
    afterRead(file) {
      file.status = "uploading";
      file.message = "上传中...";
      let param = new FormData();
      param.append("file", file.file);
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: "上传图片中...",
      });
      // 此时可以自行将文件上传至服务器
      console.log(file.file.name);
      imageUpload(param)
        .then((res) => {
          file.data = res;
          console.log(res);
          this.$toast.clear();
          file.status = "done";
          file.message = "上传成功";
        })
        .catch((err) => {
          console.log(err);
          file.status = "failed";
          file.message = "上传失败";
        });
    },
    change() {
      if (this.act == 1) {
        this.act = 2;
      } else {
        this.act = 1;
      }
    },
    // 用户须知
    prompt() {
      Dialog.alert({
        title: "用户须知",
        message:
          "预约成功后，请保持电话通畅，集体上门时间以与通气人员电话沟通确认为准，请确认热水器、灶具已连接金属波纹管、厨房门已安装完成。",
        messageAlign: "left",
      }).then(() => {
        // on close
      });
    },
    getUserInfo(res) {
      sessionStorage.setItem("ZJCD-UserInfo", res);
      this.userInfo = JSON.parse(res);
      this.initData();
    },
    initData() {
      //   alert(JSON.stringify(this.userInfo))
      let params = {
        uid: this.userInfo.userId,
        appId: 1234,
      };
      queryListUser(params).then((res) => {
        if (res && res.length > 0) {
          this.detail = res[0];
          this.form.consName = this.detail.name;
        } else {
          this.$router.replace({ name: "RqfyIndex", query: { type: 5 } });
        }
      });
    },
    jump() {
      this.$router.replace({ name: "Usermanage", query: { type: 5 } });
    },
    // 清空表单数据
    clear() {
      this.act = 1;
      this.form.consNo = "";
      this.form.mobile = "";
      this.form.appointDate = "";
      this.form.remark = "";
      this.form.fileIdList = [];
      this.form.cardBackFileId = "";
      this.form.cardFrontFileId = "";
      this.fileList = [];
      this.fileList1 = [];
      this.cardFront = [];
      this.cardBack = [];
    },
    // 预约安检
    submit() {
      if (this.act == 2) {
        this.form.consNo = this.detail.consNo;
        this.form.fileIdList = [];
        this.form.cardFrontFileId = "";
        this.form.cardBackFileId = "";
        if (this.fileList && this.fileList.length > 0) {
          this.fileList.map((item) => {
            this.form.fileIdList.push(item.data);
          });
        }
        if (this.fileList1 && this.fileList1.length > 0) {
          this.fileList1.map((item) => {
            this.form.fileIdList.push(item.data);
          });
        }
        if (this.cardFront && this.cardFront.length > 0) {
          this.form.cardFrontFileId = this.cardFront[0].data;
        }
        if (this.cardBack && this.cardBack.length > 0) {
          this.form.cardBackFileId = this.cardBack[0].data;
        }
        if (
          this.form.consName &&
          this.form.consNo &&
          this.form.mobile &&
          this.form.appointDate &&
          this.form.remark &&
          this.form.fileIdList &&
          this.form.fileIdList.length > 0 &&
          this.form.cardBackFileId &&
          this.form.cardFrontFileId
        ) {
          console.log(this.form);
          appointVentilation(this.form)
            .then((res) => {
              console.log(res);
              if (res) {
                Toast(res || "预约成功！");
                this.clear();
              }
            })
            .catch(() => {
              this.clear();
            });
        } else {
          Toast("请填写完整表单!");
        }
      } else {
        Toast("请先阅读并同意用户须知!");
      }
    },
  },
  mounted() {
    window.getUserInfo = this.getUserInfo;
  },
};
</script>

<style lang="stylus" scoped>
.van-uploader {
  margin: 10px 0 0 10px;
}

.fire {
  height: 100vh;
  overflow: auto;

  .safe {
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);
    height: calc(100vh - 120px);
    overflow-y: auto;
  }

  .content {
    background: #f04c3f;
    width: 100%;
    height: 260px;
    padding: 40px;
    box-sizing: border-box;

    .top {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 40px;

      .name {
        width: 140px;
        font-size: 40px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #fff;
      }
    }

    .user {
      display: flex;
      align-items: center;

      img {
        width: 32px;
        height: 32px;
        margin-right: 15px;
      }

      .num {
        font-size: 32px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #fff;
      }
    }

    .add {
      display: flex;
      align-items: center;
      margin-top: 20px;

      img {
        width: 32px;
        height: 32px;
        margin-right: 15px;
      }

      .address {
        font-size: 32px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #fff;
      }
    }
  }

  .anjian {
    background: #fff;

    .title {
      width: 100%;
      height: 80px;
      background: #FFFFFF;
      font-size: 28px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 600;
      color: #333333;
      line-height: 80px;
      border-bottom: 1px solid #F3F6F9;
      padding: 0 30px;
      box-sizing: border-box;
    }

    .tips {
      display: flex;
      justify-content: flex-end;
      width: 100%;
      box-sizing: border-box;
      font-size: 22px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #EB4E3F;
    }

    .instructions {
      border-top: 1px solid #F3F6F9;
      font-size: 24px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #333333;
      line-height: 3;
      padding: 0 20px;
      box-sizing: border-box;
      margin-bottom: 40px;

      img {
        width: 24px;
        height: 24px;
        margin-right: 10px;
      }

      span {
        color: #EB4E3F;
      }
    }
  }

  .button {
    display: flex;
    flex-direction: column;
    position: fixed;
    bottom: 0;
    width: 100%;
    left: 0px;
    box-sizing: border-box;
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);
  }
}
</style>