<template>
  <div class="enterprise">
    <NavHeader color="#0687D2" title="企业信息" @back="$router.go(-1)" />
    <van-form class="form">
      <div class="section">
        <van-field v-model="form1.enterpriseName" label="企业名称" required placeholder="请填写企业名称"
          :rules="[{ required: true, message: '请填写企业名称' }]" />
        <van-field v-model="form1.organizationCode" label="组织机构代码" required placeholder="请填写组织机构代码"
          :rules="[{ required: true, message: '请填写组织机构代码' }]" />
        <van-field label="企业纳税地" :value="form1.payTaxesArea" @click="showPicker = true" required readonly
          placeholder="请选择企业纳税地" />
        <van-popup v-model="showPicker" position="bottom" round>
          <van-picker show-toolbar :columns="
            columns.map((item) => {
              return item.label;
            })
          " title="企业纳税地" @cancel="showPicker = false" @confirm="onConfirm" />
        </van-popup>
        <van-field v-model="form1.contactUser" label="联系人" required readonly placeholder="请填写联系人"
          :rules="[{ required: true, message: '请填写联系人' }]" />
        <van-field v-model="form1.contactMobile" label="联系方式" required readonly placeholder="请填写联系方式" :rules="[
          { pattern, required: true, message: '请填写正确的手机号码' },
        ]" />
      </div>
      <div class="section">
        <van-field label="上传企业营业执照或事业单位法人登记证" required>
          <template #input>
            <van-uploader :after-read="afterRead" v-model="form1.businessLicenseList" max-count="10" />
          </template>
        </van-field>
      </div>
      <div class="section">
        <van-field label="上传单位申报人才购房补贴汇总表" required>
          <template #input>
            <van-uploader :after-read="afterRead" v-model="form1.summarySheetList" max-count="10" />
          </template>
        </van-field>
        <van-field @click="
          download()
        ">
          <template #input>
            <van-icon name="down">下载汇总表及个人申请表模板</van-icon>
          </template>
        </van-field>
      </div>
    </van-form>
    <div class="operation">
      <van-button v-if="
        this.form1.enterpriseName &&
        this.form1.organizationCode &&
        this.form1.payTaxesArea &&
        this.form1.contactUser &&
        this.form1.contactMobile &&
        this.form1.businessLicenseList.length > 0 &&
        this.form1.summarySheetList.length > 0
      " class="button" block color="#BFBFBF" @click="del">
        重填
      </van-button>
      <van-button v-if="
        this.form1.enterpriseName &&
        this.form1.organizationCode &&
        this.form1.payTaxesArea &&
        this.form1.contactUser &&
        this.form1.contactMobile &&
        this.form1.businessLicenseList.length > 0 &&
        this.form1.summarySheetList.length > 0
      " block color="#0687D2" @click="ensure">
        确定
      </van-button>
    </div>
  </div>
</template>

<script>
import NavHeader from "@/components/NavHeader";
import Vue from "vue";
import { Button, Field, Form, Icon, Uploader, Dialog, Picker, Popup } from "vant";
import { uploadFile } from "@/api/talents";
import {
  queryMattersEnterpriseHouse,
  saveMattersEnterpriseHouse,
} from "@/api/policy";
// import { encryptByDES } from "@/utils/utils";

Vue.use(Form).use(Button).use(Field).use(Uploader).use(Icon).use(Picker).use(Popup);
export default {
  components: { NavHeader },
  data() {
    return {
      form1: {
        enterpriseName: '',
        organizationCode: '',
        payTaxesArea: '',
        contactUser: '',
        contactMobile: '',
        businessLicenseList: [],
        summarySheetList: [],
      },
      showPicker: false,
      columns: [
        {
          id: "1",
          label: "京口区",
        }, {
          id: "2",
          label: "润州区",
        }, {
          id: "3",
          label: "丹徒区",
        }, {
          id: "4",
          label: "镇江新区",
        }, {
          id: "5",
          label: "镇江高新区",
        },
      ],
      pictureList: [],
      departmentCode: "",
      guideId: "",
      talentCode: "",
      matterType: "",
      userInfo: {},
      pattern:
        /^(13[0-9]|14[5-9]|15[012356789]|166|17[0-8]|18[0-9]|19[8-9])[0-9]{8}$/,
    };
  },
  methods: {
    init() {
      let params = {
        guideId: this.guideId,
        // userId: encryptByDES(this.userInfo.userId, "MnuYbhGv"),
      };
      queryMattersEnterpriseHouse(params).then((res) => {
        console.log(res);
        if (res.data) {
          this.form1 = res.data;
          this.form1.businessLicenseList = res.data.pictureList
            .filter(item => {
              return item.pictureType == 1;
            })
            .map(item => {
              return { url: item.picture, pictureType: item.pictureType };
            })
          this.form1.summarySheetList = res.data.pictureList
            .filter(item => {
              return item.pictureType == 2;
            })
            .map(item => {
              return { url: item.picture, pictureType: item.pictureType };
            })
        } else {
          this.form1.contactUser = this.userInfo.realName;
          this.form1.contactMobile = this.userInfo.mobileNo;
        }
      });
    },
    onConfirm(value, index) {
      // console.log(value, index)
      this.form1.payTaxesArea = this.columns[index].label;
      this.showPicker = false;
    },
    // 下载汇总表模板
    download() {

      if (window.android !== undefined) {
        let url = "https://www.smart-zj.cn:55901/image/单位申报人才购房补贴汇总表及个人申请表android"
        window.android.downLoadFile(url);
      } else {
        let url = "https://www.smart-zj.cn:55901/image/rencaihuizongbiao.xlsx"
        window.webkit &&
          window.webkit.messageHandlers.downLoadFile.postMessage(
            `${url}|showNav`
          );
      }
    },
    // 此时可以自行将文件上传至服务器
    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 = "上传失败";
        });
    },
    // 删除信息
    del() {
      this.$dialog
        .confirm({
          message: "确定重填所填信息?",
          showCancelButton: true,
        })
        .then(() => {
          // on confirm
          this.form1.enterpriseName = ""; // 企业名称
          this.form1.organizationCode = ""; // 组织机构代码
          this.form1.payTaxesArea = "";
          this.form1.businessLicenseList = []; // 登记证
          this.form1.summarySheetList = []; // 汇总表
        })
        .catch(() => {
          // on cancel
        });
    },
    // 确定
    ensure() {
      let a = [];
      [
        {
          i: this.form1.businessLicenseList.map((item) => {
            return item.url;
          }),
          type: 1,
        }, //登记证
        {
          i: this.form1.summarySheetList.map((item) => {
            return item.url;
          }),
          type: 2,
        }, //汇总表
      ].forEach((item) => {
        item.i.forEach((item1) => {
          a.push({ picture: item1, pictureType: item.type });
          return a;
        });
      });
      this.pictureList = a;
      console.log(this.pictureList);
      let params = {
        contactMobile: this.userInfo.mobileNo,
        contactUser: this.userInfo.realName,
        enterpriseAddress: "",
        enterpriseName: this.form1.enterpriseName,
        enterpriseState: 0,
        guideId: this.guideId,
        organizationCode: this.form1.organizationCode,
        payTaxesArea: this.form1.payTaxesArea,
        pictureList: this.pictureList,
        // userId: this.userInfo.userId,
      };
      saveMattersEnterpriseHouse(params).then((res) => {
        console.log(res);
        Dialog.confirm({
          message: "保存成功",
        }).then(() => {
          this.$router.go(-1);
        });
      });
    },
    // 获取userInfo信息
    getUserInfo(res) {
      sessionStorage.setItem("ZJCD-UserInfo", res);
      this.userInfo = JSON.parse(res);
    },
  },
  mounted() {
    window.getUserInfo = this.getUserInfo;
  },
  created() {
    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.departmentCode = this.$route.query.departmentCode;
    this.guideId = this.$route.query.guideId;
    this.talentCode = this.$route.query.talentCode;
    this.matterType = this.$route.query.matterType;
    this.userInfo = this.$route.query.userInfo;

    this.init();
  },
};
</script>

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

  .section {
    margin-bottom: 20px;
  }
}

.operation {
  display: flex;
  padding: 20px 30px;
  justify-content: space-between;

  .button {
    margin-right: 20px;
  }
}
</style>