<template>
  <div style="height: 100vh">
    <NavHeader
      color="#0687D2"
      title="人才“镇兴”行动购住房契税补贴申请"
      @back="$router.go(-1)"
    />
    <van-form :class="['form',type === 'view' ? 'form1' : 'form2']" @submit="onSubmit" ref="form">
      <div class="section">
        <van-field
          v-if="form.state === 4 && form.refusalCause"
          v-model="form.refusalCause"
          class="reason"
          rows="1"
          autosize
          readonly
          type="textarea"
        />
        <!-- <van-field
          v-model="form.refusalCause"
          class="reason"
          :disabled="type === 'view'"
          readonly
        /> -->
        <van-field
          v-model="form.name"
          label="姓名"
          :disabled="type === 'view'"
          readonly
          required
          placeholder="请填写姓名"
          :rules="[{ required: true, message: '请填写姓名' }]"
        />
        <van-field
          v-model="form.idCard"
          label="身份证"
          :disabled="type === 'view'"
          readonly
          required
          placeholder="请填写身份证"
          :rules="[{ required: true, message: '请填写姓名' }]"
        />
        <van-field
          v-model="form.phone"
          label="手机号码"
          :disabled="type === 'view'"
          required
          placeholder="请填写手机号码"
          :rules="[
            { required: true, message: '请填写手机号码' },
            { pattern: phoneReg, message: '请输入正确内容' }
          ]"
        />
      </div>
      <div class="section">
        <!-- <van-field
          v-model="form.unit"
          label="工作单位"
          :disabled="type === 'view'"
          required
          placeholder="请填写工作单位"
          :rules="[{ required: true, message: '请填写工作单位' }]"
        /> -->
        <van-field
          v-model="form.address"
          label="联系地址"
          :disabled="type === 'view'"
          required
          placeholder="请填写联系地址"
          :rules="[{ required: true, message: '请填写联系地址' }]"
        />
        <van-field
          v-model="form.netSignTime"
          label="网签时间"
          :disabled="type === 'view'"
          required
          readonly
          placeholder="请选择网签时间"
          @click="showDatePicker = true"
        >
        </van-field>
        <van-popup
          v-model="showDatePicker"
          position="bottom"
          round
          v-if="type !== 'view'"
        >
          <van-datetime-picker
            v-model="currentDate"
            type="date"
            title="选择网签时间"
            @confirm="(value) => oncurrentDateConfirm(value)"
            @cancel="showDatePicker = false"
          />
        </van-popup>
        <van-field
          label="不动产权证号"
          v-model="form.realEstateCard"
          required
          :disabled="type === 'view'"
          v-if="type === 'view'"
        />
        <van-field label="不动产权证号" :disabled="type === 'view'" v-else>
          <template #input>
            <div class="box_megic">
              <div style="display: flex">
                <div>苏(</div>
                <van-field
                  v-model="front"
                  :disabled="type === 'view'"
                  placeholder="例:2021"
                  input-align="center"
                  type="digit"
                  :rules="[{ required: true, message: '' }]"
                  class="megic"
                ></van-field>
                <div>)</div>
              </div>
              <div style="display: flex">
                <div>镇江市不动产第</div>
                <van-field
                  v-model="after"
                  :disabled="type === 'view'"
                  placeholder="例:31515"
                  input-align="center"
                  type="digit"
                  :rules="[{ required: true, message: '' }]"
                  class="megic megic2"
                ></van-field>
                <div>号</div>
              </div>
            </div>
          </template>
        </van-field>

        <van-field
          v-model="form.realEstateAddress"
          label="不动产权坐落地址"
          :disabled="type === 'view'"
          required
          placeholder="请填写不动产权坐落地址"
          :rules="[{ required: true, message: '请填写不动产权坐落地址' }]"
        />
        <van-field
          label="契税发票号码"
          :disabled="type === 'view'"
          required
        >
          <template #input>
            <div
              class="box_megic"
              style="display:flex;align-items: center;"
            >
              <div style="display: flex">
                <div>NO.</div>
                <van-field
                  v-model="form.deedBillCode"
                  placeholder="输入契税发票号码"
                  input-align="center"
                  :disabled="type === 'view'"
                  type="digit"
                  :rules="[{ required: true, message: '' }]"
                  class="megic megic3"
                >
                </van-field>
              </div>
            </div>
          </template>
        </van-field>
        <van-field
          v-model="form.paymentDeedTaxAmount"
          name="缴纳契税金额(元)"
          label="缴纳契税金额(元)"
          :disabled="type === 'view'"
          type="number"
          clearable
          required
          placeholder="输入缴纳契税金额(元)"
        >
        </van-field>
        <van-field
          v-model="form.square"
          label="建筑面积(m²)"
          :disabled="type === 'view'"
          required
          placeholder="请填写建筑面积   单位m²"
          :rules="[{ required: true, message: '请填写建筑面积单位m²' }]"
        />

        <van-field
          v-model="form.bankCard"
          label="银行卡号"
          :disabled="type === 'view'"
          required
          placeholder="请填写银行卡号"
          :rules="[{ required: true, message: '请填写银行卡号' }]"
        />
        <van-field
          v-model="form.bank"
          label="所属银行"
          :disabled="type === 'view'"
          required
          placeholder="请填写所属银行"
          :rules="[{ required: true, message: '请填写所属银行' }]"
        />
        <van-field
          label="上传银行卡(正、反)照"
          :disabled="type === 'view'"
          required
        >
          <template #input>
            <van-uploader
              :disabled="type === 'view'"
              :deletable="type !== 'view'"
              :after-read="afterRead"
              v-model="form.bankimg"
              max-count="2"
            />
          </template>
        </van-field>
        <van-field :disabled="type === 'view'" label="身份证照片" required>
          <template #input>
            <van-uploader
              :disabled="type === 'view'"
              :deletable="type !== 'view'"
              :after-read="afterRead"
              v-model="form.idCardPicture"
              max-count="1"
            />
          </template>
        </van-field>
        <p class="tips">二手房合同：提供3、4、6页，商品房合同：提供1、2、7页</p>
        <van-field
          :disabled="type === 'view'"
          label="商品房买卖合同3张"
          required
        >
          <template #input>
            <van-uploader
              :disabled="type === 'view'"
              :deletable="type !== 'view'"
              :after-read="afterRead"
              v-model="form.contract"
              max-count="3"
            />
          </template>
        </van-field>
        <van-field :disabled="type === 'view'" label="不动产权证书" required>
          <template #input>
            <van-uploader
              :disabled="type === 'view'"
              :deletable="type !== 'view'"
              :after-read="afterRead"
              v-model="form.certificate"
              max-count="1"
            />
          </template>
        </van-field>
        <van-field :disabled="type === 'view'" label="契税完税凭证" required>
          <template #input>
            <van-uploader
              :disabled="type === 'view'"
              :deletable="type !== 'view'"
              :after-read="afterRead"
              v-model="form.voucher"
              max-count="1"
            />
          </template>
        </van-field>
        <van-field
          :disabled="type === 'view'"
          label="上传一年以上劳动合同的上传项目"
          required
        >
          <template #input>
            <van-uploader
              :disabled="type === 'view'"
              :deletable="type !== 'view'"
              :after-read="afterRead"
              v-model="form.labour"
            />
          </template>
        </van-field>
      </div>
    </van-form>
    <div>
      <van-button
        v-if="type === 'add'"
        block
        color="#0687D2"
        @click="$refs.form.submit()"
      >
        提交
      </van-button>
      <van-button
        v-if="type === 'edit'"
        block
        color="#0687D2"
        @click="$refs.form.submit()"
      >
        修改
      </van-button>
    </div>
  </div>
</template>

<script>
import NavHeader from "@/components/NavHeader";
import { phoneReg } from "@/utils/constant";
import { decryptByDES } from "@/utils/utils";
import Vue from "vue";
import { Form, Field, Popup, Picker, Uploader, Button, Icon, DatetimePicker } from "vant";
import { uploadFile } from "@/api/talents";

import {
  mattersHousingAdd,
  mattersHousingGet,
  mattersHousingUpdate
} from "@/api/policy";

Vue.use(Form)
  .use(Field)
  .use(Popup)
  .use(Picker)
  .use(Uploader)
  .use(Button)
  .use(Icon)
  .use(DatetimePicker);

export default {
  components: { NavHeader },
  data() {
    return {
      phoneReg,
      type: null,
      form: {
        square: "",
        appId: 1234,
        departmentCode: null,
        guideId: null,
        talentCode: null,
        userId: null,
        housingType: null,
        refusalCause: "", // 驳回原因
        state: "", //状态码
        name: "", // 姓名
        idCard: "", // 身份证号
        // unit: "", // 工作单位
        address: "", // 联系地址
        phone: "", // 手机号码
        netSignTime: "", // 网签时间
        realEstateCard: "", // 不动产权证号
        realEstateAddress: "", // 不动产权坐落地址
        bankCard: "", // 银行卡号
        bank: "", // 所属银行
        deedBillCode: "", //契税发票号码
        paymentDeedTaxAmount: "", // 缴纳契税金额
        bankimg: [], //银行卡照片
        idCardPicture: [], // 身份证照片
        contract: [], // 商品房买卖合同
        certificate: [], // 不动产权证书
        voucher: [], // 契税完税凭证
        labour: [] // 劳动合同上传项目
      },
      front: "",
      after: "",
      currentDate: new Date(),
      showDatePicker: false,
      date: "",
    };
  },
  created() {
    let res = sessionStorage.getItem("ZJCD-UserInfo");
    this.userInfo = JSON.parse(res) || {};
    this.form.departmentCode = this.$route.query.departmentCode || "";
    this.form.guideId = this.$route.query.guideId;
    this.form.talentCode = this.$route.query.talentCode;
    this.form.housingType = this.$route.query.matterType === 5 ? 2 : 3;
    this.form.name = this.userInfo.realName;
    this.form.phone = this.userInfo.mobileNo;
    this.form.userId = this.userInfo.userId;
    console.log("userInfo--", this.userInfo);
    this.form.idCard =
      decryptByDES(this.userInfo.idCardNo, "MnuYbhGv").toUpperCase() ||
      this.userInfo.idCardNo;
    // 修改时用
    console.log("this.$route.query.code----", this.$route.query.code);
    this.code = this.$route.query.code;
    this.type = this.$route.query.type;
    console.log("this.code---", this.code);
    if (this.code) {
      this.init();
    }
  },
  methods: {
    init() {
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: "加载中..."
      });
      mattersHousingGet({ appId: 1234, code: this.code }).then(res => {
        console.log("进页面的第一次调用------", res);
        this.$toast.clear();
        this.form.refusalCause = res.data.refusalCause;
        this.form.state = res.data.state;
        this.form.name = res.data.name;
        this.form.square = res.data.square;
        this.form.bank = res.data.bank;
        this.form.bankCard = res.data.bankCard;
        this.form.address = res.data.address;
        this.form.code = res.data.code;
        this.form.housingType = res.data.housingType;
        this.form.idCard = res.data.idCard;
        this.form.realEstateCard = res.data.realEstateCard;
        this.form.realEstateAddress = res.data.realEstateAddress;
        this.form.netSignTime = res.data.netSignTime;
        this.form.paymentDeedTaxAmount = res.data.paymentDeedTaxAmount;
        this.form.deedBillCode = res.data.deedBillCode
        this.form.unit = res.data.unit;
        this.front = res.data.realEstateCard.substr(
          res.data.realEstateCard.indexOf("("),
          res.data.realEstateCard.indexOf(")")
        );
        this.after = res.data.realEstateCard.substr(
          res.data.realEstateCard.indexOf("第"),
          res.data.realEstateCard.indexOf("号")
        );
        res.data.pictureList.forEach(item => {
          console.log("item---", item);

          if (item.pictureType === 1) {
            this.form.idCardPicture.push({ url: item.picture });
          } else if (
            item.pictureType === 2 ||
            item.pictureType === 3 ||
            item.pictureType === 4
          ) {
            this.form.contract.push({ url: item.picture });
          } else if (item.pictureType === 5) {
            this.form.certificate.push({ url: item.picture });
          } else if (item.pictureType == 6) {
            this.form.voucher.push({ url: item.picture });
          } else if (item.pictureType == 7)  {
            this.form.labour.push({ url: item.picture });
          } else if (item.pictureType == 8) {
            this.form.bankimg.push({ url: item.picture });
          }
        });
      });
    },
    // onFront() {
    //   this.form.realEstateCard =
    //     "苏（" + this.front + "）不动产第" + this.after + "号";
    // },
    // onAfter() {
    //   this.form.realEstateCard =
    //     "苏（" + this.front + "）不动产第" + this.after + "号";
    // },
    oncurrentDateConfirm(value) {
      this.date = value;
      console.log(this.date.getTime());
      this.form.netSignTime =
        value.getFullYear() +
        "-" +
        (value.getMonth() + 1 > 9
          ? value.getMonth() + 1
          : "0" + (value.getMonth() + 1)) +
        "-" +
        (value.getDate() > 9 ? value.getDate() : "0" + value.getDate());
      this.showDatePicker = false;
    },
    onSubmit() {
      if (this.form.netSignTime == "") {
        this.$toast("请选择网签时间");
        return;
      }
      if (this.form.paymentDeedTaxAmount == "") {
        this.$toast("请输入缴纳契税金额");
        return;
      }
      if (this.form.deedBillCode == "") {
        this.$toast("请输入契税发票号码");
        return;
      } else {
        if (this.form.deedBillCode.length != 18) {
          this.$toast("请输入正确的契税发票号码");
          return;
        }
      }
      if (this.form.bankimg.length < 2) {
        this.$toast("请上传银行卡(正、反)照");
        return;
      }
      if (this.front == "" || this.after == "") {
        this.$toast("请输入正确格式的不动产权坐落地址");
        return;
      }
      this.form.realEstateCard =
        "苏(" + this.front + ")镇江市不动产第" + this.after + "号";
      if (this.form.contract.length < 3) {
        this.$toast("请按提示正确上传商品房买卖合同图片");
        return;
      }
      if (this.form.labour < 1) {
        this.$toast("请按提示正确上传一年以上劳动合同的上传项目最少一张");
        return;
      }
      let parmas = JSON.parse(JSON.stringify(this.form));
      let labour = [];
      this.form.labour.map(item => {
        return labour.push({ pictureType: 7, picture: item.url });
      });
      console.log(labour);
      parmas.pictureList = [
        {
          pictureType: 1,
          picture: this.form.idCardPicture[0].url
        },
        {
          pictureType: 2,
          picture: this.form.contract[0].url
        },
        {
          pictureType: 3,
          picture: this.form.contract[1].url
        },
        {
          pictureType: 4,
          picture: this.form.contract[2].url
        },
        {
          pictureType: 5,
          picture: this.form.certificate[0].url
        },
        {
          pictureType: 6,
          picture: this.form.voucher[0].url
        },
        {
          pictureType: 8,
          picture: this.form.bankimg[0].url
        },
        {
          pictureType: 8,
          picture: this.form.bankimg[1].url
        },
        ...labour
        // {

        //   pictureType: 7,
        //   picture: this.form.labour[0].url
        // }
      ];
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: "加载中..."
      });
      if (this.type === "add") {
        mattersHousingAdd({ code: this.code, ...parmas }).then(res => {
          this.$toast.clear();
          this.$toast(res.data || '新增成功');
          setTimeout(() => {
            this.$router.go(-1);
          }, 500);
        });
      } else if (this.type === "edit") {
        mattersHousingUpdate(parmas).then(res => {
          this.$toast.clear();
          this.$toast(res.data || '修改成功');
          setTimeout(() => {
            this.$router.go(-1);
          }, 500);
        });
      }
    },
    afterRead(file) {
      console.log(file);
      file.status = "uploading";
      file.message = "上传中...";
      let param = new FormData();
      param.append("file", file.file);
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: "上传图片中..."
      });
      uploadFile(param)
        .then(res => {
          this.$toast.clear();
          file.status = "done";
          file.message = "上传成功";
          file.url = res;
        })
        .catch(err => {
          console.log(err);
          file.status = "failed";
          file.message = "上传失败";
        });
    }
  }
};
</script>

<style lang="stylus" scoped>
.form1{
  height: calc(100vh - 83px);
}
.form2 {
  height: calc(100vh - 173px);
}
.form {
  overflow-y: auto;

  .reason {
    color: #ee0a24;
    -webkit-text-fill-color: #ee0a24; // ios 和 安卓9.0 必须添加此属性，才会生效
  }

  .tips {
    padding: 10px 20px;
    font-size: 16px;
    color: #666;
  }

  .box_megic {
    .megic {
      width: 100px;
      padding: 0;
      margin: 0;
      border-bottom: 1px solid #888;
    }

    .megic2 {
      width: 150px;
    }
    .megic3 {
        width: 300px;
    }
  }
}
</style>
