<template>
  <view class="baseInfo">
    <view>
      <uni-forms
        class="form"
        ref="form"
        :model="form"
        :rules="rules"
        label-position="top"
        label-width="100%"
        validate-trigger="bind"
      >
        <uni-forms-item label="经营主体全称" name="fullName">
          <uni-easyinput
            v-model="form.fullName"
            placeholder="请输入经营主体全称"
          />
          <!-- <button @click="getForm()">wnefi</button> -->
        </uni-forms-item>
        <uni-forms-item label="联系人" name="contactName">
          <uni-easyinput
            v-model="form.contactName"
            placeholder="请输入联系人"
          />
        </uni-forms-item>
        <uni-forms-item label="联系人手机号" name="contactPhone">
          <uni-easyinput
            v-model="form.contactPhone"
            placeholder="请输入联系人手机号"
          />
        </uni-forms-item>
        <uni-forms-item label="经营地址" name="address">
          <view class="inputAddressTip">
            <span>{{
              "用户需确保所输入地址与匹配地址的误差不会过大（默认定位宜昌市）"
            }}</span>
          </view>
          <uni-easyinput
            v-model="address"
            :placeholder="address !== '' ? address : '请输入或选取经营地址'"
            suffixIcon="location"
            @iconClick="toAddress"
            class="uni-mt-5"
            :disabled="false"
            @focus="addressInputBlur = false"
            @blur="selectNautica"
          >
          </uni-easyinput>
          <view class="matAddressTip">
            <view class="label">
              <span> {{ "平台匹配地址：" }} </span>
            </view>
            <view class="content">
              <span> {{ form.address }} </span>
            </view>
          </view>
        </uni-forms-item>
        <uni-forms-item label="社会信用代码" name="socialCreditCode">
          <uni-easyinput
            v-model="form.socialCreditCode"
            placeholder="请输入社会信用代码"
          />
        </uni-forms-item>
        <uni-forms-item label="主体类型" width="100%" name="type">
          <uni-data-select
            v-model="form.type"
            :localdata="dictLists['sys_enterprise_type']"
            width="100%"
            placeholder="请选择主体类型"
          />
        </uni-forms-item>
        <uni-forms-item label="经营服务内容" name="serviceContent">
          <uni-data-select
            v-model="form.serviceContent"
            :localdata="dictLists['business_service_content']"
            placeholder="请选择经营服务内容"
          />
        </uni-forms-item>
        <uni-forms-item label="注册资本(万元)" name="registeredCapital">
          <uni-easyinput
            v-model="form.registeredCapital"
            placeholder="请输入注册资本(万元)"
          />
        </uni-forms-item>
        <uni-forms-item label="实缴资本(万元)" name="paidInCapital">
          <uni-easyinput
            v-model="form.paidInCapital"
            placeholder="请输入实缴资本(万元)"
          />
        </uni-forms-item>
        <uni-forms-item label="地标农产品类型" name="landmarkType">
          <select-cy
            :value="landmarkType"
            placeholder="请选择地标农产品类型"
            slabel="label"
            svalue="label"
            :options="dictLists['sys_landmark_type']"
            @change="change"
            :zindex="1"
          />
        </uni-forms-item>
        <uni-forms-item label="工商登记时间" name="registrationTime">
          <uni-datetime-picker
            type="date"
            placeholder="请选择工商登记时间"
            v-model="form.registrationTime"
          />
        </uni-forms-item>
        <uni-forms-item label="工商登记地址" name="registrationAddress">
          <uni-easyinput
            v-model="form.registrationAddress"
            placeholder="请输入工商登记地址"
          />
        </uni-forms-item>
        <uni-forms-item label="经营范围" name="natureBusiness">
          <uni-easyinput
            type="textarea"
            v-model="form.natureBusiness"
            placeholder="请输入内容"
          />
        </uni-forms-item>
        <uni-forms-item label="营业执照图片" name="businessLicenseUrl">
          <image-upload
            fileMediatype="image"
            :disable-preview="false"
            :auto-upload="true"
            limit="1"
            mode="grid"
            title="最多选择1张图片"
            v-model="businessLicenseUrl"
          >
          </image-upload>
        </uni-forms-item>
      </uni-forms>

      <view style="height: 44px">
        <button v-if="false">
          <text>{{ "测 试" }}</text>
        </button>
      </view>
    </view>

    <view v-if="true" class="foot">
      <button @click="cencel" :plain="false" class="cencel">
        <text>{{ "取 消" }}</text>
      </button>
      <button @click="showConfirm" type="primary" class="confirm">
        <text>{{ "确 认" }}</text>
      </button>
    </view>
  </view>
</template>

<script>
import { selectUserEntity } from "@/api/enterprise/userEntity";
import {
  addBaseInfo,
  updateBaseInfo,
  selectBaseInfo,
} from "@/api/enterprise/baseInfo";

import config from "@/config";

export default {
  name: "baseInfo",
  components: {},
  props: {},
  data() {
    const verificationSj = (rule, value, data, callback) => {
      return new Promise((resolve, reject) => {
        var reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
        if (!reg.test(value)) {
          reject(new Error("手机号格式错误"));
        } else {
          resolve();
        }
      });
    };
    return {
      loading: false,
      haveEnterprise: false,
      businessLicenseUrl: [],
      landmarkType: [],
      form: {},
      dictLists: {},
      rules: {
        fullName: {
          rules: [
            {
              required: true,
              errorMessage: "请输入主体名称",
            },
          ],
        },
        contactPhone: {
          rules: [
            {
              required: true,
              errorMessage: "请输入联系电话",
              validateFunction: (rule, value, data, callback) =>
                verificationSj(rule, value, data, callback),
            },
          ],
        },
        contactName: {
          rules: [
            {
              required: true,
              errorMessage: "请输入联系人",
            },
          ],
        },
        address: {
          rules: [
            {
              required: true,
              errorMessage: "请选择经营地址",
            },
          ],
        },
        type: {
          rules: [
            {
              required: true,
              errorMessage: "请选择主体类型",
            },
          ],
        },
        socialCreditCode: {
          rules: [
            {
              required: true,
              errorMessage: "请输入社会信用代码",
            },
          ],
        },
      },
      address: "",
      toIndexRoute: "pages/busEntDefend",
      addressInputBlur: true,
    };
  },
  computed: {},
  created() {
    this.getEnterprise();
    this.reset();
    this.initializeDict();
  },
  methods: {
    selectNautica() {
      let that = this;
      let _key = "838faa1c7f00ffdbe380cd9c5da5149a";
      this.addressInputBlur = true;
      uni.request({
        url: "https://restapi.amap.com/v3/geocode/geo",
        method: "GET",
        data: {
          key: _key,
          address:
            that.address !== undefined &&
            that.address !== null &&
            that.address !== ""
              ? that.address
              : "宜昌市",
          city: "yichang",
        },
        success: (res) => {
          const addDet = res.data.geocodes[0];
          that.form["address"] = addDet.formatted_address;
          that.form["lng"] = addDet.location.split(",")[0];
          that.form["lat"] = addDet.location.split(",")[1];
          that.form["adcode"] = addDet.adcode;
        },
        fail: () => {
          this.$modal.msgError("请输入正确经营地址");
        },
      });
    },
    TypeOfLandmarkType() {
      if (
        !(
          this.form.landmarkType === "" ||
          this.form.landmarkType === null ||
          this.form.landmarkType === undefined
        )
      ) {
        for (let item of this.form.landmarkType.split(",")) {
          for (let dictItem of this.dictLists.sys_landmark_type) {
            if (item === dictItem.value) {
              this.landmarkType.push(dictItem.label);
            }
          }
        }
      }
    },
    async naviBack(isNew) {
      let pages = getCurrentPages(); //关于获取页面的官方文档https://uniapp.dcloud.io/api/window/window
      let prevPage = pages[pages.length - 2];
      uni.navigateBack({
        delta: 1,
        success: () => {
          if (isNew !== undefined) {
            setTimeout(function () {
              prevPage.$vm.getMsg(isNew);
            }, 200);
          }
        },
      });
    },
    getBaseInfo() {
      this.loading = true;
      selectBaseInfo().then((response) => {
        this.form = response.data;
        if (this.form.id !== undefined) {
          this.address = this.form.address;
        }
        if (
          this.form.businessLicenseUrl === "" ||
          this.form.businessLicenseUrl === null ||
          this.form.businessLicenseUrl === undefined
        ) {
          this.$set(this.form, ["businessLicenseUrl"], []);
        } else {
          let businessLicenseUrl = [];
          businessLicenseUrl.push(this.form.businessLicenseUrl);
          this.$set(this.form, ["businessLicenseUrl"], businessLicenseUrl);
          this.businessLicenseUrl = businessLicenseUrl;
        }
        this.loading = false;
        this.TypeOfLandmarkType();
      });
    },
    getEnterprise() {
      selectUserEntity().then((response) => {
        this.options = response.data;
        if (response.data.length !== 0) {
          this.haveEnterprise = true;
        } else {
          this.haveEnterprise = false;
        }
      });
    },
    cencel() {
      this.naviBack();
    },
    reset() {
      this.form = {
        id: null,
        fullName: null,
        type: null,
        contactName: null,
        contactPhone: null,
        address: null,
        landmarkType: [],
        socialCreditCode: null,
        serviceContent: null,
        registeredCapital: null,
        paidInCapital: null,
        registrationTime: null,
        registrationAddress: null,
        natureBusiness: null,
        businessLicenseUrl: [],
        addTime: null,
        editTime: null,
        status: "0",
        adcode: null,
        lng: null,
        lat: null,
      };
    },
    change(item, value) {
      let landVessel = [];
      this.form.landmarkType = landVessel;
      this.landmarkType = value;
    },
    async initializeDict() {
      this.dictByType("business_service_content");
      this.dictByType("sys_enterprise_type");
      this.dictByType("sys_landmark_type");
    },
    getForm(form) {
      if (
        form !== undefined &&
        JSON.stringify(form) !== "{}" &&
        Object.keys(form).length !== 0
      ) {
        this.form = Object.assign(this.form, form);
        this.address = this.form.address;
      } else {
        // console.error("getForm()参数尚未初始化");
      }
    },
    toAddress() {
      uni.navigateTo({
        url: "/pages/index/selAddress/index",
      });
    },
    dictByType(type) {
      this.getDicts(type).then((response) => {
        let dicts = [];
        for (let dict of response.data) {
          let element = {};
          element["value"] = dict.dictValue;
          element["text"] = dict.dictLabel;
          element["label"] = dict.dictLabel;
          dicts.push(element);
        }
        this.$set(this.dictLists, type, dicts);
      });
    },
    submitForm() {
      for (let item of this.landmarkType) {
        for (let dictItem of this.dictLists.sys_landmark_type) {
          if (item === dictItem.label) {
            this.form.landmarkType.push(dictItem.value);
          }
        }
      }
      let form = this.form;
      let isNew =
        this.form.id === null ||
        this.form.id === undefined ||
        this.form.id === "";
      if (isNew) {
        if (form.landmarkType !== null && form.landmarkType.length !== 0) {
          form.landmarkType = form.landmarkType.toString(",");
        }
        if (this.businessLicenseUrl.length === 0) {
          form.businessLicenseUrl = "";
        } else {
          form.businessLicenseUrl = this.businessLicenseUrl.toString(",");
        }
        addBaseInfo(form)
          .then((response) => {
            setTimeout(function () {
              that.$modal.msgSuccess("新增成功");
            }, 10);
            if (
              getCurrentPages()[getCurrentPages().length - 2].route ===
              this.toIndexRoute
            ) {
              uni.reLaunch({
                url: "/pages/index",
              });
            } else {
              this.naviBack();
            }
          })
          .catch((res) => {
            console.log(res);
            setTimeout(function () {
              that.$modal.msgError("新增失败！");
            }, 10);
          });
      } else {
        if (form.landmarkType !== null && form.landmarkType.length !== 0) {
          form.landmarkType = form.landmarkType.toString(",");
        } else {
          form.landmarkType = "";
        }
        if (this.businessLicenseUrl.length === 0) {
          form.businessLicenseUrl = "";
        } else {
          form.businessLicenseUrl = this.businessLicenseUrl.toString(",");
        }
        updateBaseInfo(form)
          .then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.naviBack(isNew);
          })
          .catch((err) => {
            // console.error(err);
            setTimeout(function () {
              that.$modal.msgError("修改失败！");
            }, 10);
          });
      }
    },
    showConfirm() {
      this.$refs["form"].validate().then((res) => {
        this.$cus_modal.confirm().then((conf_res) => {
          if (conf_res.confirm === true) {
            this.submitForm();
          }
        });
      });
    },
  },
  watch: {
    haveEnterprise: {
      handler: function (val, oldVal) {
        if (this.haveEnterprise === true) {
          this.getBaseInfo();
        }
      },
      deep: true,
    },
    loading: {
      handler: function (val, oldVal) {
        if (val === true) {
          this.$modal.loading("加载中，请耐心等待...");
        } else {
          this.$modal.closeLoading();
        }
      },
      deep: true,
    },
  },
  mounted() {},

  // 页面周期函数--监听页面加载
  onLoad() {},
  // 页面周期函数--监听页面初次渲染完成
  onReady() {},
  // 页面周期函数--监听页面显示(not-nvue)
  onShow() {},
  // 页面周期函数--监听页面隐藏
  onHide() {},
  // 页面周期函数--监听页面卸载
  onUnload() {
    const that = this
    return that.$listenOB.goBack()
  },
  // 页面处理函数--监听用户下拉动作
  // onPullDownRefresh() { uni.stopPullDownRefresh(); },
  // 页面处理函数--监听用户上拉触底
  // onReachBottom() {},
  // 页面处理函数--监听页面滚动(not-nvue)
  // onPageScroll(event) {},
  // 页面处理函数--用户点击右上角分享
  // onShareAppMessage(options) {},
};
</script>

<style lang="scss" scoped>
page {
  background: white;
}

.form {
  text-align: center;
  margin: auto;
  width: 80%;
}

.baseInfo {
  background-color: white;
  // height: calc(100%);

  /deep/ .uni-forms-item {
    .uni-forms-item__content {
      .uni-file-picker {
        .uni-file-picker__header {
          .file-title {
            span {
              color: #ff0000a6;
            }
          }
        }
      }

      .uni-mt-5 {
        .uni-icons {
          background: #007aff21;
          line-height: 35px;
          height: 35px;
        }
      }

      .uni-select-cy {
        z-index: 1;

        .uni-select-cy-select {
          z-index: -500;
        }
      }

      .inputAddressTip {
        color: #aab1b3;
        text-align: left;
        font-size: 0.9em;
      }

      .matAddressTip {
        display: flex;
        justify-content: flex-start;
        font-size: 0.7em;
        flex-wrap: wrap;

        .label {
          color: #c8c8c8;
        }

        .content {
          color: rgb(0, 153, 255);
        }
      }
    }
  }

  .foot {
    width: 100vw;
    height: 44px;
    bottom: 0px;
    display: flex;
    position: fixed;
    z-index: 2;
    .cencel {
      border-radius: 0px;
      border: 0px;
      width: 50%;
      background-color: white;
    }

    .confirm {
      border-radius: 0px;
      border: 0px;
      width: 50%;
      color: white;
    }
  }
}
</style>
