<template>
  <div class="bg-F5">
    <div class="container">
      <div class="partTitle">
        <span class="orangeLine"></span
        >{{ $t("page.views.shops.enter.index.title1") }}
      </div>
      <el-form
        class="formPanel"
        ref="form"
        :model="form"
        :rules="rules"
        label-width="280px"
      >
        <div class="formTitle">
          {{ $t("page.views.shops.enter.add.accountInfo") }}
          <span class="subTitle"
            >（{{ $t("page.views.shops.enter.add.useLoginSystem") }}）</span
          >
        </div>
        <el-form-item
          class="formItem"
          :label="`${$t(`page.views.shops.enter.add.userName`)}`"
          prop="loginName"
        >
          <el-input v-model="form.loginName"></el-input>
        </el-form-item>
        <el-form-item
          class="formItem"
          :label="`${$t(`page.views.shops.enter.add.password`)}`"
          prop="password"
        >
          <el-input show-password v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item
          class="formItem"
          :label="`${$t(`page.views.shops.enter.add.surepassword`)}`"
          prop="surepassword"
        >
          <el-input show-password v-model="form.surepassword"></el-input>
        </el-form-item>

        <div class="line"></div>
        <div class="formTitle">
          {{ $t("page.views.shops.enter.add.companyInfo") }}
        </div>
        <el-form-item
          class="formItem"
          :label="`${$t(`page.views.shops.enter.add.companyName`)}`"
          prop="companyName"
        >
          <el-input v-model="form.companyName"></el-input>
        </el-form-item>
        <el-form-item
          class="formItem"
          :label="`${$t(`page.views.shops.enter.add.companyType`)}`"
          prop="companyType"
        >
          <el-select
            v-model="form.companyType"
            :placeholder="`${$t(`pleaseChoose`)}`"
          >
            <el-option
              v-for="{ key, value } in companyType"
              :key="`companyType${value}`"
              :label="key"
              :value="value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          class="formItem"
          :label="`${$t(`page.views.shops.enter.add.primaryBusiness`)}`"
          prop="primaryBusiness"
        >
          <el-input v-model="form.primaryBusiness"></el-input>
        </el-form-item>

        <el-form-item
          class="formItem"
          :label="`${$t(`page.views.shops.enter.add.companyAddress`)}`"
        >
          <el-select
            class="quyuSel"
            v-model="province"
            :placeholder="
              `${$t(`pleaseChoose`)}${$t(
                `page.views.shops.enter.add.province`
              )}`
            "
          >
            <el-option v-for="x in provinces" :key="x" :label="x" :value="x" />
          </el-select>
          <el-select
            class="quyuSel"
            v-model="city"
            :placeholder="
              `${$t(`pleaseChoose`)}${$t(`page.views.shops.enter.add.city`)}`
            "
          >
            <el-option v-for="x in citys" :key="x" :label="x" :value="x" />
          </el-select>
          <el-select
            class="quyuSel"
            v-model="area"
            :placeholder="
              `${$t(`pleaseChoose`)}${$t(`page.views.shops.enter.add.area`)}`
            "
          >
            <el-option v-for="x in areas" :key="x" :label="x" :value="x" />
          </el-select>
        </el-form-item>
        <el-form-item
          class="formItem"
          :label="`${$t(`page.views.shops.enter.add.detailAddress`)}`"
          prop="detailAddress"
        >
          <el-input v-model="address"></el-input>
        </el-form-item>
        <el-form-item
          class="formItem"
          :label="
            `${$t(`pleaseChoose`)}${$t(
              `page.views.shops.enter.add.longitude`
            )}${$t(`page.views.shops.enter.add.latitude`)}`
          "
          prop="jwd"
        >
          <div class="longLatDiv">
            <span>{{ $t("page.views.shops.enter.add.longitude") }}</span>
            <el-input class="input" v-model="form.longitude"></el-input>
          </div>
          <div class="longLatDiv">
            <span>{{ $t("page.views.shops.enter.add.latitude") }}</span>
            <el-input class="input" v-model="form.latitude"></el-input>
          </div>
          <el-button class="submitBtn" @click="toggerMap">{{
            mapVisible
              ? $t("page.views.shops.enter.add.close")
              : $t("page.views.shops.enter.add.choose")
          }}</el-button>
          <div :class="{ map: true, show: mapVisible }" id="map"></div>
        </el-form-item>
        <el-form-item
          class="formItem"
          :label="`${$t(`page.views.shops.enter.add.legalPerson`)}`"
          prop="legalPerson"
        >
          <el-input v-model="form.legalPerson"></el-input>
        </el-form-item>
        <el-form-item
          class="formItem"
          :label="`${$t(`page.views.shops.enter.add.contactNumber`)}`"
          prop="contactNumber"
        >
          <el-input v-model="form.contactNumber"></el-input>
        </el-form-item>
        <el-form-item
          class="formItem"
          :label="`${$t(`page.views.shops.enter.add.establishDate`)}`"
          prop="establishDate"
        >
          <el-date-picker
            v-model="form.establishDate"
            type="date"
            value-format="yyyy-MM-dd"
            :placeholder="
              `${$t(`pleaseChoose`)}${$t(
                `page.views.shops.enter.add.establishDate`
              )}`
            "
          />
        </el-form-item>
        <el-form-item
          class="formItem"
          :label="`${$t(`page.views.shops.enter.add.unifiedSocialCreditCode`)}`"
          prop="unifiedSocialCreditCode"
        >
          <el-input v-model="form.unifiedSocialCreditCode"></el-input>
        </el-form-item>
        <el-form-item
          class="formItem"
          :label="`${$t(`page.views.shops.enter.add.companyIntroduction`)}`"
          prop="companyIntroduce"
        >
          <el-input type="textarea" v-model="form.companyIntroduce"></el-input>
        </el-form-item>
        <el-form-item
          class="formItem"
          :label="`${$t(`page.views.shops.enter.add.businessLicense`)}`"
          prop="businessLicenseUrl"
        >
          <el-upload
            list-type="picture-card"
            :action="`${$basePath}/common/upload`"
            :before-upload="beforeUpload"
            :on-preview="preview"
            :on-remove="remove"
            :on-success="
              ({ data: { fileName } }, { uid }) =>
                success('businessLicenseUrl', fileName, uid)
            "
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <div class="info">
            {{ $t("page.views.shops.enter.add.message3") }}
          </div>
        </el-form-item>
        <el-form-item
          class="formItem"
          :label="`${$t(`page.views.shops.enter.add.defaultImg`)}`"
          prop="defaultImgUrl"
        >
          <el-upload
            :class="{ uploadHide: form.defaultImgUrl }"
            list-type="picture-card"
            :action="`${$basePath}/common/upload`"
            :before-upload="beforeUpload"
            :on-preview="preview"
            :on-remove="remove"
            :on-success="
              ({ data: { fileName } }, { uid }) =>
                success('defaultImgUrl', fileName, uid)
            "
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item
          class="formItem"
          :label="`${$t(`page.views.shops.enter.add.propagandaImg`)}`"
          prop="propagandaImgUrl"
        >
          <el-upload
            list-type="picture-card"
            :action="`${$basePath}/common/upload`"
            :before-upload="beforeUpload"
            :on-preview="preview"
            :on-remove="remove"
            :on-success="
              ({ data: { fileName } }, { uid }) =>
                success('propagandaImgUrl', fileName, uid)
            "
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>

        <div class="line"></div>
        <el-form-item class="formItem tc">
          <el-button class="submitBtn" @click="validate">{{
            $t("page.views.shops.enter.add.submit")
          }}</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-dialog :visible.sync="showImg">
      <img width="100%" :src="showImgSrc" alt="" />
    </el-dialog>
  </div>
</template>
<script lang="ts">
interface IFile {
  type: string;
  url: string;
  uid: number;
}
import { Component, Vue, Watch } from "vue-property-decorator";
import dict from "@/store/modules/dict";
import { provinces, getCity, getArea } from "@/api/area";
import BMap from "BMap";
import { RegAccount } from "@/utils";
import { ElForm } from "element-ui/types/form";
import i18n from "@/lang";
@Component({ name: "shopEnterAdd" })
export default class extends Vue {
  private form: IAny = {
    longitude: "",
    latitude: "",
    detailAddress: "",
    defaultImgUrl: ""
  };
  private province = "";
  private city = "";
  private area = "";
  private address = "";
  private map: any = null;
  private local: any = null;
  private mapVisible = false;
  private showImg = false;
  private showImgSrc = "";
  private fileList: IFile[] = [];
  private rules = {
    loginName: [
      {
        required: true,
        message: `${i18n.t(`page.views.shops.enter.add.accountInfo`)}`,
        trigger: "blur"
      },
      {
        validator: (rule: any, value: string, callback: any) =>
          callback(
            RegAccount.test(value)
              ? undefined
              : new Error(`${i18n.t(`page.views.shops.enter.add.regAccount`)}`)
          ),
        trigger: "blur"
      }
    ],
    password: [
      {
        required: true,
        message: `${i18n.t(`page.views.shops.enter.add.password`)}`,
        trigger: "blur"
      },
      {
        validator: (rule: any, value: string, callback: any) =>
          callback(
            RegAccount.test(value)
              ? undefined
              : new Error(`${i18n.t(`page.views.shops.enter.add.regAccount`)}`)
          ),
        trigger: "blur"
      }
    ],
    surepassword: [
      {
        required: true,
        message: `${i18n.t(`page.views.shops.enter.add.surepassword`)}`,
        trigger: "blur"
      },
      {
        validator: (rule: any, value: string, callback: any) => {
          if (value === "") {
            callback(new Error(`${i18n.t(`page.views.shops.enter.add.err1`)}`));
          } else if (value !== this.form.password) {
            callback(new Error(`${i18n.t(`page.views.shops.enter.add.err2`)}`));
          } else {
            callback();
          }
        },
        trigger: "blur"
      }
    ],
    companyName: [
      {
        required: true,
        message: `${i18n.t(`inputPlaceholder`)}${i18n.t(
          `page.views.shops.enter.add.companyName`
        )}`,
        trigger: "blur"
      }
    ],
    companyType: [
      {
        required: true,
        message: `${i18n.t(`pleaseChoose`)}${i18n.t(
          `page.views.shops.enter.add.companyType`
        )}`,
        trigger: "blur"
      }
    ],
    primaryBusiness: [
      {
        required: true,
        message: `${i18n.t(`inputPlaceholder`)}${i18n.t(
          `page.views.shops.enter.add.primaryBusiness`
        )}`,
        trigger: "blur"
      }
    ],

    detailAddress: [
      {
        required: true,
        message: `${i18n.t(`inputPlaceholder`)}${i18n.t(
          `page.views.shops.enter.add.detailAddress`
        )}`,
        trigger: "blur"
      }
    ],
    jwd: [
      {
        validator: (rule: any, value: any, callback: any) => {
          if (!this.form.longitude)
            return callback(
              new Error(
                `${i18n.t(`inputPlaceholder`)}${i18n.t(
                  `page.views.shops.enter.add.longitude`
                )}`
              )
            );
          if (!this.form.latitude)
            return callback(
              new Error(
                `${i18n.t(`inputPlaceholder`)}${i18n.t(
                  `page.views.shops.enter.add.latitude`
                )}`
              )
            );

          callback();
        }
      }
    ],
    legalPerson: [
      {
        required: true,
        message: `${i18n.t(`inputPlaceholder`)}${i18n.t(
          `page.views.shops.enter.add.legalPerson`
        )}`,
        trigger: "blur"
      }
    ],
    contactNumber: [
      {
        required: true,
        message: `${i18n.t(`inputPlaceholder`)}${i18n.t(
          `page.views.shops.enter.add.contactNumber`
        )}`,
        trigger: "blur"
      }
    ],
    establishDate: [
      {
        required: true,
        message: `${i18n.t(`page.views.shops.enter.add.establishDate`)}`,
        trigger: "blur"
      }
    ],
    unifiedSocialCreditCode: [
      {
        required: true,
        message: `${i18n.t(`inputPlaceholder`)}${i18n.t(
          `page.views.shops.enter.add.unifiedSocialCreditCode`
        )}`,
        trigger: "blur"
      }
    ],
    companyIntroduce: [
      {
        required: true,
        message: `${i18n.t(`inputPlaceholder`)}${i18n.t(
          `page.views.shops.enter.add.companyIntroduction`
        )}`,
        trigger: "blur"
      }
    ],
    businessLicenseUrl: [
      {
        validator: (rule: string, value: any, callback: any) => {
          if (!this.form.businessLicenseUrl)
            return callback(
              new Error(
                `${i18n.t(`pleaseUpload`)}${i18n.t(
                  `page.views.shops.enter.add.businessLicense`
                )}`
              )
            );

          callback();
        }
      }
    ],
    defaultImgUrl: [
      {
        validator: (rule: string, value: any, callback: any) => {
          if (!this.form.defaultImgUrl)
            return callback(
              new Error(
                `${i18n.t(`pleaseUpload`)}${i18n.t(
                  `page.views.shops.enter.add.defaultImg`
                )}`
              )
            );

          callback();
        }
      }
    ],
    propagandaImgUrl: [
      {
        validator: (rule: string, value: any, callback: any) => {
          if (!this.form.propagandaImgUrl)
            return callback(
              new Error(
                `${i18n.t(`pleaseUpload`)}${i18n.t(
                  `page.views.shops.enter.add.propagandaImg`
                )}`
              )
            );
          callback();
        }
      }
    ]
  };

  get provinces() {
    return provinces;
  }
  get citys() {
    this.city = "";
    return getCity(this.province);
  }
  get areas() {
    this.area = "";
    return getArea(this.province, this.city);
  }
  get companyType() {
    return dict.companyType;
  }
  get detailAddress() {
    return `${this.province} ${this.city} ${this.area} ${this.address}`;
  }
  get DomForm() {
    return this.$refs.form as ElForm;
  }
  @Watch("detailAddress")
  detailAddressChange() {
    this.mapVisible && this.local.search(this.detailAddress);
    this.form.detailAddress = this.detailAddress;
  }
  @Watch("fileList")
  fileListChange() {
    let obj: IAny = {
      businessLicenseUrl: "",
      defaultImgUrl: "",
      propagandaImgUrl: ""
    };
    this.fileList.forEach(({ type, url }) => {
      obj[type] = `${
        type !== "defaultImgUrl" && obj[type] ? `${obj[type]},` : ""
      }${url}`;
    });
    Object.assign(this.form, obj);
    Object.keys(obj).forEach(x => this.DomForm.validateField(x));
  }

  @Watch("form.longitude")
  @Watch("form.latitude")
  jwdChange() {
    this.DomForm.validateField("jwd");
  }
  mounted() {
    this.map = new BMap.Map("map", { minZoom: 8, maxZoom: 16 });
    const point = new BMap.Point(116.341603, 39.957202);
    this.map.centerAndZoom(point, 13);
    this.map.addControl(
      new BMap.MapTypeControl({
        mapTypes: [BMAP_NORMAL_MAP, BMAP_HYBRID_MAP]
      })
    );
    this.map.enableScrollWheelZoom(true);
    this.map.addEventListener("click", (e: any) => {
      this.map.clearOverlays();
      const pt = e.point;
      this.map.addOverlay(new BMap.Marker(pt));
      this.form.longitude = pt.lng;
      this.form.latitude = pt.lat;
    });
    this.local = new BMap.LocalSearch(this.map, {
      onSearchComplete: () => {
        if (this.local.getResults().getPoi(0)) {
          const pp = this.local.getResults().getPoi(0).point; //获取第一个智能搜索的结果
          this.map.centerAndZoom(pp, 18);
          this.map.addOverlay(new BMap.Marker(pp)); //添加标注
          this.form.longitude = pp.lng;
          this.form.latitude = pp.lat;
        } else {
          this.$message(`${i18n.t(`page.views.shops.enter.add.message1`)}`);
        }
      }
    });
  }

  toggerMap() {
    if (this.mapVisible) return (this.mapVisible = false);
    this.mapVisible = true;
    this.local.search(this.detailAddress);
  }
  validate() {
    this.DomForm.validate(x => x && this.submit());
  }
  async submit() {
    const [err] = await this.$post("/company/enter", this.form);
    if (err) return;
    this.DomForm.resetFields();
    this.$message.success(`${i18n.t(`page.views.shops.enter.add.message2`)}`);
    this.$router.push("/shopEnter");
  }
  success(type: string, url: string, uid: number) {
    this.fileList.push({ type, url, uid });
  }
  remove({ uid }: any) {
    this.fileList = this.fileList.filter(x => uid !== x.uid);
  }
  preview({ url }: any) {
    this.showImgSrc = url;
    this.showImg = true;
  }

  beforeUpload(file: any) {
    console.log(file.type);
    if (/image\/(png|jpe?g)$/.test(file.type)) return true;
    this.$message.error(`${this.$i18n.t("message.error.imgUpload")}`);
    return false;
  }
}
</script>
<style scoped lang="scss">
.partTitle {
  padding: 3rem 0 2rem 0;
  font-size: 1.8rem;
  color: #333;
  .orangeLine {
    display: inline-block;
    height: 1.8rem;
    width: 0.3rem;
    background: #fd5522;
    vertical-align: middle;
    border-radius: 0.15rem;
    margin-right: 1rem;
  }
}
.formPanel {
  background: #fff;
  padding: 2rem;
  box-sizing: border-box;
  z-index: 1;
  border-radius: 0.4rem;
  margin-bottom: 4rem;
  .formItem {
    width: 80%;
    .quyuSel {
      width: 31%;
      margin-right: 3.5%;
      &:last-child {
        margin-right: 0;
      }
    }
    .info {
      height: 2.4rem;
      line-height: 2.4rem;
      font-size: 1.2rem;
      color: #999;
    }
  }
  .formTitle {
    font-size: 1.6rem;
    color: #333;
    padding-bottom: 4rem;
    .subTitle {
      color: #999;
    }
  }
  .line {
    width: 100%;
    height: 0.1rem;
    background: #e5e5e5;
    margin: 3rem 0 2rem 0;
  }
  .submitBtn {
    color: #fff;
    background: #fd5522;
    border-color: #fd5522;
  }
  .longLatDiv {
    width: 40%;
    float: left;
    margin-right: 1rem;
    .input {
      width: 80%;
      margin-left: 1rem;
    }
  }
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.uploadIconDiv {
  width: 12rem;
  height: 12rem;
  text-align: center;
  padding: 3.4rem 0;
  box-sizing: border-box;
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
  }
  .txt {
    height: 2.4rem;
    line-height: 2.4rem;
    font-size: 1.4rem;
    color: #333;
  }
}
.map {
  width: 100%;
  height: 50rem;
  position: absolute;
  top: 5rem;
  left: 0;
  z-index: 1;
  display: none;
  &.show {
    display: block;
  }
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.tc {
  text-align: center;
}
</style>
<style lang="scss">
.formPanel {
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .distpicker-address-wrapper select {
    width: 32%;
  }
}
.uploadHide {
  .el-upload {
    display: none;
  }
}
</style>
