<template>
  <d2-container v-loading="isLoading">
    <div class="addHouser-container">
      <el-form :model="form"
               label-width="120px"
               ref="form"
               :rules="rules">
        <el-form-item label="商家名称："
                      prop="companyName">
          <el-input v-model="form.companyName"
                    placeholder="请填写"
                    autocomplete="off"
                    maxlength="50"
                    :show-word-limit="true"
                    class="filter-item-same-width" />
        </el-form-item>
        <el-form-item label="机构编码：">
          <el-input v-model="form.companyCode"
                    placeholder="请填写"
                    autocomplete="off"
                    maxlength="50"
                    :show-word-limit="true"
                    class="filter-item-same-width" />
        </el-form-item>
        <el-form-item label="商家性质："
                      prop="nature">
          <el-select v-model="form.nature"
                     placeholder="请选择"
                     class="filter-item-same-width">
            <el-option v-for="item in businessNatureList"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="商家类型："
                      prop="businessType">
          <el-select v-model="form.businessType"
                     placeholder="请选择"
                     class="filter-item-same-width">
            <el-option v-for="item in businessTypeList"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="有效期："
                      prop="a">
          <el-date-picker v-model="value1"
                          type="date"
                          :picker-options="pickerOptions"
                          format="yyyy 年 MM 月 dd 日"
                          value-format="yyyy-MM-dd 00:00:00"
                          placeholder="选择日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="营业执照：">
          <update-image v-model="form.businessLicenseImageList"
                        :limitKb="2048"
                        :drag="true"
                        :isShowTip="false">
          </update-image>
          <div class="zhu">注：图片格式为png、jpg，大小不超过2MB</div>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer"
          class="dialog-footer">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary"
                 style="margin-left: 150px"
                 :loading="ifSubmit"
                 @click="submit('form')">保存</el-button>
    </span>
  </d2-container>
</template>

<script>
import { mapState, mapActions } from "vuex";
import {
  getNature,
  getBusinessType,
  modiyBusiness,
  addBusiness,
  getBusiness,
} from "@/libs/common/constant";
import { selectList, generateTiemList, weekList } from "@/utils/json";
export default {
  data() {
    return {
      openid: this.$route.params.id,
      isLoading: false,
      ifSubmit: false,
      form: {
        companyName: "",
        companyCode: "",
        nature: "",
        businessType: "",
        businessLicenseImageList: "",
        a: "111",
      },
      value1: "",
      // 商家性质
      businessNatureList: [],
      // 商家类型
      businessTypeList: [],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        },
      },
      rules: {
        companyName: [{ required: true, message: "请填写", trigger: "blur" }],
        contactName: [{ required: true, message: "请填写", trigger: "blur" }],
        a: [{ required: true, message: "请填写", trigger: "change" }],

        nature: [{ required: true, message: "请选择", trigger: "change" }],
        businessType: [
          { required: true, message: "请选择", trigger: "change" },
        ],
      },
    };
  },
  async created() {
    if (this.openid) {
      this.isLoading = true;
      await this.getConstant();
      await this.getBusiness();
    } else {
      await this.cancel();
    }
  },
  computed: {
    // 获取 此页面 路径
    ...mapState("d2admin/page", ["current"]),
  },
  methods: {
    ...mapActions("d2admin/page", ["close", "add"]),
    // 获取 基本信息
    async getBusiness() {
      const res = await this.$api.GET(`${getBusiness.url}${this.openid}`);
      this.form = { ...res.info, ...res.company };
      this.value1 = this.form.validUntil;
      // this.value1 = "2024-09-11 00:00:00";
      this.form.a = "111";
      this.isLoading = false;
    },

    // 获取字典数据
    async getConstant() {
      await this.getNatureList();
      await this.getBusinessTypeList();
    },
    selectList(myJson, a) {
      return selectList(myJson, a);
    },
    // 获取 商家性质
    async getNatureList() {
      const res = await this.$api.GET(`${getNature.url}`);
      this.businessNatureList = this.selectList(res, true);
    },
    // 获取 商家类型
    async getBusinessTypeList() {
      const res = await this.$api.GET(`${getBusinessType.url}`);
      this.businessTypeList = this.selectList(res);
    },

    async cancel() {
      var tagName = this.current;
      await this.close({ tagName });
      this.$router.push("/businessList");
    },
    validatePhoneNumber(phoneNumber) {
      var pattern = /^1[3456789]\d{9}$/;
      return pattern.test(phoneNumber);
    },
    submit(detail) {
      if (!this.validatePhoneNumber(this.form.contactPhone)) {
        this.$message.error("请输入正确的手机号！！！");
        return;
      }
      if (this.ifSubmit) {
        return;
      }
      this.ifSubmit = true;
      this.$refs[detail].validate(async (valid) => {
        if (valid) {
          try {
            // 提交前 处理 数据
            // 拼接 营业时间 转换 时间
            var data = await this.arrangeData();
            // 判断 参数 确定是修改还是 添加
            if (this.openid) {
              console.log(data, "编辑提交的参数");
              //  提交接口
              data.companyOpenId = this.openid;
              const res = await this.$api.POST(`${modiyBusiness.url}`, data);
            } else {
              console.log(data, "添加提交的参数");
            }
            await this.cancel();
            this.$message({
              type: "success",
              message: "操作成功!",
            });
          } catch (error) {}
        } else {
          console.log("error submit!!");
          this.ifSubmit = false;
          return false;
        }
      });
    },
    arrangeData() {
      // if (this.form.validUntil != this.form.value1) {
      //   this.form.validUntil = dayjs(this.form.value1).format(
      //     "YYYY-MM-DD 00:00:00"
      //   );
      // }

      var data = {
        companyName: this.form.companyName,
        provinceId: this.form.provinceId,
        cityId: this.form.cityId,
        countyId: this.form.countyId,
        townId: this.form.townId,
        contactName: this.form.contactName,
        contactPhone: this.form.contactPhone,
        loginName: this.form.loginName,
        loginPwd: this.form.loginPwd,
        merchantId: this.form.merchantId,
        merchantName: this.form.merchantName,
        nature: this.form.nature,
        businessType: this.form.businessType,
        validUntil: this.value1,
        payRate: this.form.payRate,
        serviceRate: this.form.serviceRate,
        addrDetail: this.form.addrDetail,
        businessHours: this.form.businessHours,
        // 非必填
        companyCode: this.form.companyCode,

        merchantName: this.form.merchantName,
      };
       if(this.form.businessLicenseImageList){
       data.businessLicenseImageList = this.form.businessLicenseImageList
      }
      return data;
    },
  },
};
</script>

<style lang="scss" scoped>
</style>
