<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-row :gutter="10"
                  style="width: 800px">
            <el-col :span="5">
              <el-form-item label=""
                            prop="provinceId">
                <el-select v-model="form.provinceId"
                           :loading="isLoadProvinceId"
                           loading-text="信息加载中"
                           @change="provinceIdChange"
                           placeholder="选择省"
                           style="margin-left: -7px">
                  <el-option v-for="item in provinceIdList"
                             :key="item.id"
                             :label="item.name"
                             :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label=""
                            prop="cityId">
                <el-select v-model="form.cityId"
                           @change="cityIdChange"
                           placeholder="选择市">
                  <el-option v-for="item in cityIdList"
                             :key="item.id"
                             :label="item.name"
                             :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label=""
                            prop="countyId"
                            placeholder="选择区/县">
                <el-select v-model="form.countyId"
                           @change="fourChange">
                  <el-option v-for="item in countyIdList"
                             :key="item.id"
                             :label="item.name"
                             :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="5"
                    v-if="isFourChage">
              <el-form-item label=""
                            prop="countyId"
                            placeholder="选择乡镇">
                <el-select v-model="form.townId">
                  <el-option v-for="item in fourIdList"
                             :key="item.id"
                             :label="item.name"
                             :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="详细地址："
                      prop="addrDetail">
          <el-input v-model="form.addrDetail"
                    placeholder="请填写"
                    autocomplete="off"
                    maxlength="30"
                    :show-word-limit="true"
                    class="filter-item-same-width" />
        </el-form-item>

        <el-form-item label="营业时间："
                      prop="a"
                      style="width: 600px">
          <el-col :span="11">
            <el-select v-model="form.startWeek"
                       placeholder="请选择">
              <el-option v-for="item in weekList"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="2"
                  class="line">至</el-col>
          <el-col :span="11">
            <el-select v-model="form.endWeek"
                       placeholder="请选择">
              <el-option v-for="item in weekList"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label=""
                      prop="name"
                      style="width: 600px">
          <el-col :span="11">
            <el-select v-model="form.startTime"
                       placeholder="请选择">
              <el-option v-for="item in timeList"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="2"
                  class="line">-</el-col>
          <el-col :span="11">
            <el-select v-model="form.endTime"
                       placeholder="请选择">
              <el-option v-for="item in timeList"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>

        <el-form-item label="负责人："
                      prop="contactName">
          <el-input v-model="form.contactName"
                    placeholder="请填写"
                    autocomplete="off"
                    maxlength="30"
                    :show-word-limit="true"
                    class="filter-item-same-width" />
        </el-form-item>

        <el-form-item label="联系电话："
                      prop="contactPhone">
          <el-input v-model="form.contactPhone"
                    placeholder="请填写"
                    autocomplete="off"
                    maxlength="30"
                    :show-word-limit="true"
                    class="filter-item-same-width" />
        </el-form-item>
        <el-form-item label="联系邮箱："
                      prop="email">
          <el-input v-model="form.email"
                    placeholder="请填写"
                    autocomplete="off"
                    maxlength="30"
                    :show-word-limit="true"
                    class="filter-item-same-width" />
          <div class="zhu">
            注：此邮箱后续会作为接收电子账单使用，请认真填写
          </div>
        </el-form-item>

        <el-form-item label="有效期："
                      prop="value1">
          <el-date-picker v-model="form.value1"
                          type="date"
                          :picker-options="pickerOptions"
                          placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="账户名称："
                      prop="loginName">
          <el-input v-model="form.loginName"
                    placeholder="请填写"
                    autocomplete="off"
                    maxlength="30"
                    :show-word-limit="true"
                    class="filter-item-same-width" />
        </el-form-item>
        <el-form-item label="登录密码："
                      prop="loginPwd">
          <el-input v-model="form.loginPwd"
                    placeholder="请填写"
                    autocomplete="off"
                    maxlength="30"
                    :show-word-limit="true"
                    class="filter-item-same-width" />
          <div class="zhu">注：密码应为数字+字母混排,字母区分大小写</div>
        </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-item label="支付费率："
                      prop="payRate">
          <el-input placeholder="请填写"
                    type="number"
                    :step="0.1"
                    v-model="form.payRate"
                    max="99.9"
                    min="0.1"
                    class="filter-item-same-width">
            <template slot="append">%</template>
          </el-input>
          <div class="zhu">
            注：费率设置单位为百分数，最小基本单位为0.1，有效数据0.1-99.9之间
          </div>
        </el-form-item>
        <el-form-item label="服务费率："
                      prop="serviceRate">
          <el-input placeholder="请填写"
                    type="number"
                    :step="0.1"
                    v-model="form.serviceRate"
                    max="99.9"
                    min="0.1"
                    class="filter-item-same-width">
            <template slot="append">%</template>
          </el-input>
          <div class="zhu">
            注：费率设置单位为百分数，最小基本单位为0.1，有效数据0.1-99.9之间
          </div>
        </el-form-item>

        <el-form-item label="微信商户号："
                      prop="merchantId">
          <el-input placeholder="请填写"
                    v-model="form.merchantId"
                    autocomplete="off"
                    maxlength="30"
                    :show-word-limit="true"
                    class="filter-item-same-width">
          </el-input>
        </el-form-item>

        <el-form-item label="商户号名称："
                      prop="">
          <el-input placeholder="请填写"
                    v-model="form.merchantName"
                    autocomplete="off"
                    maxlength="30"
                    :show-word-limit="true"
                    class="filter-item-same-width">
          </el-input>
          <div class="zhu">
            注：收款账户为平台服务商下申请的支付商户号，请谨慎填写！！
          </div>
        </el-form-item>
        <!-- <el-form-item label="测试">
          <el-button @click="ls()">测试</el-button>
        </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,
  jdAddressCascader,
  addBusiness,
  getBusiness,
} from "@/libs/common/constant";
import { selectList, generateTiemList, weekList } from "@/utils/json";
import dayjs from "dayjs";
export default {
  data() {
    return {
      isLoading: false,
      form: {
        companyName: "", // 商家名称
        companyCode: "", // 机构编码
        nature: "", // 商家性质
        businessType: "", // 商家类型
        provinceId: "",
        cityId: "",
        countyId: "",
        townId: "0",
        addrDetail: "", // 详细地址
        contactName: "", // 公司联系人
        contactPhone: "", // 联系人电话
        email: "", // 联系邮箱
        loginName: "", // 账户名
        loginPwd: "", // 账户密码
        merchantId: "", // 商户号
        merchantName: "", // 商户号名称
        value1: "",
        validUntil: "", // 有效期
        startWeek: "",
        endWeek: "",
        startTime: "",
        endTime: "",
        businessHours: "",
        businessLicenseImageList: "", // 营业执照图片
        payRate: "", // 支付费率
        serviceRate: "", // 服务费率
        a: "1111",
      },
      // 商家性质
      businessNatureList: [],
      // 商家 类型
      businessTypeList: [],
      // 地址
      isLoadProvinceId: true,
      // 一级
      provinceIdList: [],
      // 二级
      cityIdList: [],
      // 三级
      countyIdList: [],
      // 四级
      fourIdList: [],
      // 四级地址是否显示
      isFourChage: false,
      weekList: [],
      timeList: [],
      startWeek: "",
      endWeek: "",
      startTime: "",
      endTime: "",
      // 禁用今天之前的日期
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        },
      },
      ifSubmit: false,

      // 编辑
      editId: this.$route.params.id,
      rules: {
        companyName: [{ required: true, message: "请填写", trigger: "blur" }],
        contactName: [{ required: true, message: "请填写", trigger: "blur" }],
        contactPhone: [{ required: true, message: "请填写", trigger: "blur" }],
        email: [{ required: true, message: "请填写", trigger: "blur" }],
        value1: [{ required: true, message: "请填写", trigger: "blur" }],
        loginName: [{ required: true, message: "请填写", trigger: "blur" }],
        loginPwd: [{ required: true, message: "请填写", trigger: "blur" }],
        payRate: [{ required: true, message: "请填写", trigger: "blur" }],
        serviceRate: [{ required: true, message: "请填写", trigger: "blur" }],
        merchantId: [{ required: true, message: "请填写", trigger: "blur" }],
        nature: [{ required: true, message: "请选择", trigger: "change" }],
        businessType: [
          { required: true, message: "请选择", trigger: "change" },
        ],
        a: [{ required: true, message: "请填写", trigger: "blur" }],
        provinceId: [{ required: true, message: "请选择", trigger: "change" }],
        cityId: [{ required: true, message: "请选择", trigger: "change" }],
        countyId: [{ required: true, message: "请选择", trigger: "change" }],
        addrDetail: [{ required: true, message: "请填写", trigger: "blur" }],
      },
    };
  },
  async created() {
    // 获取 字典 数据
    await this.getConstant();
    if (this.editId) {
      // 传过来 openid  获取 详情
      this.isLoading = true;
      await this.getBusiness(this.editId);
    }
  },
  computed: {
    // 获取 此页面 路径
    ...mapState("d2admin/page", ["current"]),
  },
  methods: {
    ...mapActions("d2admin/page", ["close", "add"]),
    // 获取 字典数据
    async getConstant() {
      await this.getNatureList();
      await this.getBusinessTypeList();
      this.provinceIdList = await this.getProvinceList();
      this.timeList = await this.generateTiemList();
      this.weekList = await this.weekLista();
    },
    selectList(myJson, a) {
      return selectList(myJson, a);
    },
    weekLista() {
      return weekList;
    },
    generateTiemList() {
      return generateTiemList();
    },
    // 获取 商家性质
    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 getProvinceList() {
      const res = await this.$api.GET(`${jdAddressCascader.url}`);
      this.isLoadProvinceId = false;
      return res;
    },
    // 获取 二级 地址
    async getCityList(provinceId) {
      const res = await this.$api.GET(`${jdAddressCascader.url2}${provinceId}`);
      return res;
    },
    // 获取 三级 地址
    async getCountyId(cityId) {
      const res = await this.$api.GET(`${jdAddressCascader.url3}${cityId}`);
      return res;
    },
    // 获取 四级 地址
    async getfourList(countyId) {
      const res = await this.$api.GET(`${jdAddressCascader.url4}${countyId}`);
      console.log(res, "我被调用了");
      return res;
    },
    // 二级地址赋值
    async provinceIdChange() {
      this.cityIdList = await this.getCityList(this.form.provinceId);
      this.form.cityId = "";
      this.form.countyId = "";
    },
    // 三级 地址 赋值
    async cityIdChange() {
      this.countyIdList = await this.getCountyId(this.form.cityId);
      this.form.countyId = "";
    },
    // 四级 地址 赋值
    async fourChange() {
      this.fourIdList = await this.getfourList(this.form.countyId);
      if (this.fourIdList.length > 0) {
        this.isFourChage = true;
        this.form.townId = "";
      } else {
        this.isFourChage = false;
        this.form.townId = 0;
      }
    },
    async cancel() {
      var tagName = this.current;
      await this.close({ tagName });
      this.$router.push("/businessList");
    },
    ls() {
      var data = {
        companyName: "12315z",
        provinceId: "1",
        cityId: "72",
        countyId: "2799",
        townId: "0",
        contactName: "124214z1",
        contactPhone: "15673701001",
        loginName: "zzx131",
        loginPwd: "123456z",
        merchantId: "1659484214",
        merchantName: "大学城餐厅12334",
        nature: "1",
        businessType: "1",
        validUntil: "2025-01-15 00:00:00",
        payRate: "3",
        serviceRate: "3",
      };
      this.addBusiness(data);
    },
    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.editId) {
              console.log(data, "编辑提交的参数");
              //  提交接口
              this.form.openId = this.editId;
              const res = await this.$api.POST(`${addBusiness.url}`, data);
            } else {
              console.log(data, "添加提交的参数");
              // 提交 接口
              await this.addBusiness(data);
            }
            await this.cancel();
            this.$message({
              type: "success",
              message: "操作成功!",
            });
          } catch (error) {}
        } else {
          console.log("error submit!!");
          this.ifSubmit = false;
          return false;
        }
      });
    },
    // 整理数据
    arrangeData() {
      this.form.businessHours = `周${this.form.startWeek}至周${this.form.endWeek},${this.form.startTime}:00至${this.form.endTime}:00`;
      this.form.validUntil = dayjs(this.form.value1).format(
        "YYYY-MM-DD 00:00:00"
      );
      var list = [];
      if (this.form.businessLicenseImageList) {
        list[0] = this.form.businessLicenseImageList;
      }
      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.form.validUntil,
        payRate: this.form.payRate,
        serviceRate: this.form.serviceRate,
        addrDetail: this.form.addrDetail,
        businessHours: this.form.businessHours,
        email: this.form.email,
        // 非必填
        companyCode: this.form.companyCode,
        businessLicenseImageList: list || [],
        merchantName: this.form.merchantName,
      };
      return data;
    },
    // 添加
    async addBusiness(data) {
      const res = await this.$api.POST(`${addBusiness.url}`, data);
      console.log(res, "123");
    },

    // 编辑
    // 获取 详情
    async getBusiness(openId) {
      const res = await this.$api.GET(`${getBusiness.url}${openId}`);
      this.form = { ...res.company, ...res.info };
      await this.provinceIdChange();
      this.form.cityId = res.company.cityId;
      await this.cityIdChange();
      this.form.countyId = res.company.countyId;
      await this.fourChange();
      this.form.townId = res.company.townId;
      if (this.form.businessHours) {
        let arr = [...this.form.businessHours];
        this.form.startWeek = arr[1];
        this.form.endWeek = arr[4];
        this.form.startTime = arr[6] + arr[7];
        this.form.endTime = arr[12] + arr[13];
      }
      this.form.loginName = res.company.userList[0].loginName;
      this.form.loginPwd = res.company.userList[0].loginPwd;
      console.log(this.form);
      this.isLoading = false;
      console.log(res);
    },
  },
};
</script>

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