<template>
  <div class="check">
    <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>
        <div class="tips">提示：具体时间以师傅联系您确定为准</div>
        <van-field
          v-model="form.remark"
          rows="2"
          autosize
          required
          label="故障描述"
          type="textarea"
          maxlength="100"
          placeholder="请填写对上门师傅的备注信息"
          show-word-limit
        />
        <van-uploader
          style="magin-left: 30px"
          v-model="fileList"
          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,
} from "vant";
import { queryListUser, imageUpload, appointSecurityCheck } from "@/api/rqfy.js";
Vue.use(Button)
  .use(Field)
  .use(Popup)
  .use(DatetimePicker)
  .use(Uploader)
  .use(Dialog)
  .use(Toast);
export default {
  name: "check",
  data() {
    return {
      detail: {},
      userInfo: {},
      form: {
        consNo: "",
        consName: "",
        mobile: "",
        appointDate: "",
        remark: "",
        fileIdList: [],
      },
      fileList: [],
      showcurrentDatePicker: false,
      minDate: new Date(),
      currentDate: new Date(), // 期望日期
      act: 1,
    };
  },
  created() {
    if (this.$route.query.type == 4) {
      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);
      } 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() {
      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: 4 } });
        }
      });
    },
    jump() {
      this.$router.replace({ name: "Usermanage", query: { type: 4 } });
    },
    // 清空表单数据
    clear() {
      this.act = 1;
      this.form.consNo = "";
      this.form.mobile = "";
      this.form.appointDate = "";
      this.form.remark = "";
      this.form.fileIdList = [];
      this.fileList = [];
    },
    // 预约安检
    submit() {
      console.log(this.fileList);
      if (this.act == 2) {
        this.form.consNo = this.detail.consNo;
        this.form.fileIdList = [];
        if (this.fileList && this.fileList.length > 0) {
          this.fileList.map((item) => {
            this.form.fileIdList.push(item.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
        ) {
          console.log(this.form);
          appointSecurityCheck(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;
}

.check {
  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%;
      padding: 0 30px;
      box-sizing: border-box;
      font-size: 22px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #EB4E3F;
      line-height: 1.2;
      border-bottom: 1px solid #F3F6F9;
    }

    .instructions {
      border-top: 1px solid #F3F6F9;
      font-size: 24px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #333333;
      line-height: 2;
      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>