<template>
  <ContainerTit>
    <div slot="headr">
      <el-button v-if="!shopId" @click="delPauseSave(1)">清除暂存</el-button>
      <el-button v-if="!shopId" :loading="loading" @click="temData(true)">
        暂存
      </el-button>
      <el-button type="primary" :loading="loading" @click="addShop(false)">
        提交保存
      </el-button>
    </div>
    <div class="detail-tab-item" style="padding: 20px">
      <el-form
        ref="form"
        size="small"
        :model="form"
        :rules="rules"
        label-width="140px"
      >
        <el-row>
          <el-col :span="14">
            <el-form-item prop="logo" label="商铺LOGO">
              <UploadQiniu
                :file-list="img_list"
                @uploadSuccess="uploadSuccess"
                @handleRemove="uploadRemove"
              />
            </el-form-item>
            <el-form-item label="商铺编码">
              <el-input
                v-model="form.shopCode"
                disabled
                placeholder="系统自动创建"
                style="width: 300px"
              ></el-input>
            </el-form-item>
            <el-form-item label="商铺名称" prop="name">
              <el-input
                v-model="form.name"
                placeholder="商铺名称"
                style="width: 300px"
              ></el-input>
            </el-form-item>
            <el-form-item label="仓库" prop="warehouseId">
              <el-button type="primary" @click="warehouse_show = true">
                选择仓库
              </el-button>
              <div style="display: inline-block; margin-left: 10px">
                <el-tag
                  v-for="(item, index) in useWarehouseNameArr"
                  :key="index"
                  closable
                  @close="closeTag(index)"
                >
                  {{ item.warehouseName }}
                </el-tag>
              </div>
            </el-form-item>
            <el-form-item label="商铺类型" prop="shopType">
              <el-select
                v-model="form.shopType"
                placeholder="商铺类型"
                style="width: 300px"
              >
                <el-option
                  v-for="item in type_options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <!--            <el-form-item label="成本算法" prop="costType">-->
            <!--              <el-select-->
            <!--                v-model="form.costType"-->
            <!--                style="width: 300px"-->
            <!--                :disabled="!!shopId"-->
            <!--                placeholder="成本算法"-->
            <!--              >-->
            <!--                <el-option-->
            <!--                  v-for="item in cost_algorithm"-->
            <!--                  :key="item.value"-->
            <!--                  :label="item.label"-->
            <!--                  :value="item.value"-->
            <!--                ></el-option>-->
            <!--              </el-select>-->

            <!--              <el-tooltip effect="dark" placement="bottom-start">-->
            <!--                <div slot="content">-->
            <!--                  <p>-->
            <!--                    移动加权法：用于价格较为恒定的行业，每次进货的库存与金额会累加，进行成本重算-->
            <!--                  </p>-->
            <!--                  <p>-->
            <!--                    个别计价法：用于价格波动较大的行业，按批次入库，分批次出库-->
            <!--                  </p>-->
            <!--                </div>-->
            <!--                <i class="el-icon-warning-outline"></i>-->
            <!--              </el-tooltip>-->
            <!--              <div style="font-size: 12px; font-weight: normal; color: #e6a23c">-->
            <!--                温馨提示：成本算法一经设置不允许修改-->
            <!--              </div>-->
            <!--            </el-form-item>-->
            <!--            <el-form-item-->
            <!--              label="负责人"-->
            <!--              prop="shopPartnerId"-->
            <!--            >-->
            <!--              <el-input-->
            <!--                v-model="form.partnerName"-->
            <!--                placeholder="负责人"-->
            <!--                readonly-->
            <!--                style="width: 300px"-->
            <!--              >-->
            <!--                <i-->
            <!--                  @click="show_Partnership=true"-->
            <!--                  slot="suffix"-->
            <!--                  class="el-input__icon el-icon-search"-->
            <!--                ></i>-->
            <!--              </el-input>-->
            <!--              <a-->
            <!--                href="/#/SystemSettings/liansuoguanli/AddPartnership"-->
            <!--                target="_blank"-->
            <!--              > <el-button-->
            <!--                size="mini"-->
            <!--                type="text"-->
            <!--              >【新建负责人】</el-button></a>-->
            <!--            </el-form-item>-->

            <el-form-item label="商铺地址" prop="address">
              <div v-if="!!shopId && region.length > 0">
                <RegionSelect
                  v-model="region"
                  size="small"
                  style="width: 300px"
                  @getRegion="getRegion"
                  @change="regionChange"
                />
              </div>
              <div v-else>
                <RegionSelect
                  v-model="region"
                  size="small"
                  style="width: 300px"
                  @change="regionChange"
                />
              </div>
              <el-input
                v-model="form.address"
                placeholder="详细地址"
                style="width: 300px; margin-top: 10px"
              ></el-input>
            </el-form-item>
            <!--            <el-form-item label="商铺坐标">-->
            <!--              <el-input-->
            <!--                v-model="form.latitude"-->
            <!--                readonly-->
            <!--                placeholder="经度"-->
            <!--                style="width: 160px"-->
            <!--              ></el-input>-->
            <!--              <el-input-->
            <!--                v-model="form.longitude"-->
            <!--                readonly-->
            <!--                placeholder="纬度"-->
            <!--                style="width: 160px"-->
            <!--              ></el-input>-->
            <!--            </el-form-item>-->
            <el-form-item label="主营">
              <el-input
                v-model="form.describe"
                placeholder="商铺主营"
                style="width: 300px"
              ></el-input>
            </el-form-item>
            <el-form-item v-if="false" label-width="0">
              <div style="width: 800px">
                <baidu-map
                  v-if="false"
                  class="map"
                  style="height: 400px; overflow-y: auto"
                  :center="'北京'"
                  @click="mapClick"
                >
                  <!--              地区检索-->
                  <bm-local-search
                    :keyword="mapCenter"
                    :auto-viewport="true"
                    @searchcomplete="searchcomplete"
                  ></bm-local-search>
                  <!--              缩放-->
                  <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
                </baidu-map>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="营业时间" prop="openTime">
              <template>
                <el-time-picker
                  v-model="startTime"
                  format="HH:mm"
                  style="width: 130px"
                  placeholder="开始时间"
                  :disabled="!!form.openTime.isAllDay"
                  @change="startTimeChange"
                />
                <el-time-picker
                  v-model="endTime"
                  style="margin: 0 10px; width: 130px"
                  format="HH:mm"
                  placeholder="结束时间"
                  :disabled="!!form.openTime.isAllDay"
                  @change="endTimeChange"
                />
              </template>

              <el-checkbox v-model="form.openTime.isAllDay">全天</el-checkbox>
            </el-form-item>
            <el-form-item label="联系人" prop="contactName">
              <el-input
                v-model="form.contactName"
                placeholder="联系人"
                style="width: 350px"
              ></el-input>
            </el-form-item>
            <el-form-item label="联系电话" prop="mobile">
              <el-input
                v-model="form.mobile"
                placeholder="联系电话"
                style="width: 350px"
              ></el-input>
            </el-form-item>
            <el-form-item label="销售区域" prop="region">
              <el-radio-group v-model="is_all_region">
                <el-radio :label="5">全国</el-radio>
                <el-radio :label="4">部分</el-radio>
              </el-radio-group>
              <div
                v-show="is_all_region === 4"
                style="
                  border-top: 1px solid #ddd;
                  margin-top: 10px;
                  padding-top: 10px;
                "
              >
                <RegionTree
                  :already-region="already_region"
                  :checked-key="region_arr"
                  @checkChange="selRegion"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <PartnershipModel
      v-if="show_Partnership"
      :is-show-add="true"
      :is-check="false"
      :dialog-visible="show_Partnership"
      @close="show_Partnership = false"
      @confirm="PartnershipConfirm"
    />
    <!--    选择仓库-->
    <WarehouseModel
      v-if="warehouse_show"
      :is-show="warehouse_show"
      @confirm="selWarehouse"
      @cancel="warehouse_show = false"
    />
  </ContainerTit>
</template>

<script>
  import RegionSelect from "@/component/common/RegionSelectJSON";
  import PartnershipModel from "@/component/common/PartnershipModel.vue";
  import UploadQiniu from "@/component/common/UploadQiniu.vue";
  import RegionTree from "@/component/common/RegionTree";
  import WarehouseModel from "@/component/common/WarehouseModel.vue";
  import {
    getSalesAreaInEnterprise,
    getShopInfo,
    editShop,
    addShop,
  } from "@/api/Shop";
  import { getPauseSave, delPauseSave, addPauseSave } from "@/api/common";
  import { mapGetters } from "vuex";
  export default {
    name: "AddShop",
    components: {
      RegionSelect,
      RegionTree,
      PartnershipModel,
      UploadQiniu,
      WarehouseModel,
    },
    data() {
      const validateTime = (rule, value, callback) => {
        if (!value.isAllDay) {
          if (!value.start) {
            callback(new Error("请选择开始时间"));
          } else if (!value.end) {
            callback(new Error("请选择结束时间"));
          } else {
            callback();
          }
        } else {
          callback();
        }
      };
      const validatePhone = (rule, value, callback) => {
        const re = /^1[3456789]\d{9}$/; // 正则表达式
        if (value === "") {
          callback(new Error("请输入手机号!"));
        } else if (!re.test(value)) {
          callback(new Error("手机号格式有误，请重新输入!"));
        } else {
          callback();
        }
      };
      const validateRegion = (rule, value, callback) => {
        if (!this.form.salesArea.length) {
          callback(new Error("请选择销售区域"));
        } else {
          callback();
        }
      };
      return {
        warehouse_show: false,
        useWarehouseNameArr: [],
        useWarehouseName: [],
        is_all_region: 5, // 销售区域是否选择全国，默认全国
        loading: false,
        cost_algorithm: [
          {
            label: "移动加权法",
            value: 1,
          },
          {
            label: "个别计价法",
            value: 2,
          },
        ],
        region_arr: [],
        already_region: [],
        endTime: "",
        startTime: "",
        show_Partnership: false,
        region: [],
        regionName: "",
        img_list: [],
        shopId: "",
        map_center: "北京",
        type_options: [
          {
            value: 1,
            label: "联营商铺",
          },
          {
            value: 2,
            label: "直营商铺",
          },
        ],
        form: {
          logo: "",
          name: "",
          costType: "",
          shopCode: "",
          shopType: "",
          shopPartnerId: "",
          contactName: "",
          partnerName: "",
          salesArea: ["0-0-0"],
          openTime: {
            start: "",
            end: "",
            isAllDay: "",
          },
          mobile: "",
          provinceCode: "",
          cityCode: "",
          districtCode: "",
          address: "",
          describe: "",
          latitude: "",
          longitude: "",
          warehouseId: [],
        },
        isAllCountry: false,
        rules: {
          logo: [
            { required: true, message: "请上传商铺LOGO", trigger: "change" },
          ],
          name: [
            { required: true, message: "请输入商铺名称", trigger: "blur" },
          ],
          shopType: [
            { required: true, message: "请选择商铺类型", trigger: "change" },
          ],
          costType: [
            { required: true, message: "请选择成本算法", trigger: "change" },
          ],
          provinceCode: [
            { required: true, message: "请选择商铺地址", trigger: "change" },
          ],
          model: [
            { required: true, message: "请选择经营模式", trigger: "change" },
          ],
          address: [
            { required: true, message: "请输入详细地址", trigger: "blur" },
          ],
          // shopPartnerId: [
          //   { required: true, message: '请选择商铺负责人', trigger: 'blur' }
          // ],
          contactName: [
            { required: true, message: "请选择商铺联系人", trigger: "blur" },
          ],
          mobile: [
            { required: true, message: "请输入联系电话", trigger: "blur" },
            { validator: validatePhone, trigger: "blur" },
          ],
          openTime: [
            { required: true, validator: validateTime, trigger: "change" },
          ],
          region: [
            { required: true, validator: validateRegion, trigger: "change" },
          ],
          warehouseId: [
            {
              type: "array",
              required: true,
              message: "请选择仓库",
              trigger: "change",
            },
          ],
        },
        brand: "",
      };
    },
    computed: {
      ...mapGetters({
        storeData: "MUser/storeData",
        systemType: "MUser/systemType",
      }),
      mapCenter() {
        if (!this.regionName.provinceName) {
          return "";
        }
        return (
          this.regionName.provinceName +
          this.regionName.cityName +
          this.regionName.districtName +
          this.form.address
        );
      },
    },
    async created() {
      //多门店
      if ([2, 3].includes(this.systemType)) {
        this.shopId = this.storeData.id;
        //    进入客户详情
        await this.getShopInfo();
        return;
      }
      // 企业
      this.brand = this.$route.path.includes("brand");
      await this.getSalesAreaInEnterprise();
      if (this.$route.params.id) {
        this.shopId = this.$route.params.id;
        //    进入客户详情
        await this.getShopInfo();
      } else {
        await this.getTempShopData();
      }
    },
    methods: {
      //  选择仓库
      selWarehouse(row) {
        if (this.useWarehouseNameArr.length) {
          this.useWarehouseNameArr.forEach((item, index) => {
            if (Number(item.id) === row[0].id) {
              this.useWarehouseNameArr.splice(index, 1);
            }
          });
          this.useWarehouseNameArr = this.$_common.unique(
            this.useWarehouseNameArr.concat(row),
            ["id"]
          );
        } else {
          this.useWarehouseNameArr = row;
        }
        this.form.warehouseId = this.useWarehouseNameArr.map((item) => {
          return item.id;
        });
        this.useWarehouseName = this.useWarehouseNameArr.map((item) => {
          return item.warehouseName;
        });
      },
      //  关闭标签
      closeTag(index) {
        this.useWarehouseNameArr.splice(index, 1);
        this.form.warehouseId = this.useWarehouseNameArr.map((item) => {
          return item.id;
        });
      },
      // 地区检索
      getRegion(province, city, district) {
        this.regionName = {
          provinceName: province.label,
          cityName: city.label || "",
          districtName: district.label || "",
        };
      },
      // 当前企业下已有的销售区域
      async getSalesAreaInEnterprise() {
        const data = await getSalesAreaInEnterprise();

        this.already_region = data.data;
      },
      // 选择区域 树形插件
      selRegion(row) {
        this.form.salesArea = row.map((item) => {
          return item.codePath;
        });
      },
      // 选择时间
      startTimeChange(val) {
        const hours =
          val.getHours() < 10 ? "0" + val.getHours() : val.getHours();
        const minutes =
          val.getMinutes() < 10 ? "0" + val.getMinutes() : val.getMinutes();
        this.form.openTime.start = hours + ":" + minutes;
      },
      // 选择时间
      endTimeChange(val) {
        const hours =
          val.getHours() < 10 ? "0" + val.getHours() : val.getHours();
        const minutes =
          val.getMinutes() < 10 ? "0" + val.getMinutes() : val.getMinutes();
        this.form.openTime.end = hours + ":" + minutes;
      },
      // 地图
      searchcomplete(res) {
        if (!res || !res.Ir || !res.Ir[0]) return;
        const points = res.Ir[0].point;
        this.form.latitude = points.lat;
        this.form.longitude = points.lng;
      },
      // 地图组件点击事件
      mapClick({ type, target, point, pixel, overlay }) {
        this.form.latitude = point.lat;
        this.form.longitude = point.lng;
        if (overlay && overlay.z.title) {
          this.form.address = overlay.z.title;
        }
      },
      // 选择图片
      uploadSuccess(val, res, file, fileList) {
        this.form.logo = val;
      },
      uploadRemove() {
        this.form.logo = "";
      },
      // 选择合伙人
      PartnershipConfirm(val) {
        this.form.partnerName = val[0].name;
        this.form.shopPartnerId = val[0].id;
      },
      // 选择区域
      regionChange(val, params) {
        this.form.provinceCode = val[0];
        this.form.cityCode = val[1];
        this.form.districtCode = val[2];
        const provinceName = params[0].label;
        const cityName = params[1].label;
        const districtName = params[2].label;
        this.regionName = {
          provinceName: provinceName,
          cityName: cityName,
          districtName: districtName,
        };
      },

      //  商铺详情
      async getShopInfo() {
        const { data } = await getShopInfo(this.shopId);

        this.form = {
          ...data,
          warehouseId: data.warehouseId.split(","),
        };
        this.startTime = new Date(
          "1970/01/01" + "  " + data.openTime.start + ":00"
        );
        this.endTime = new Date(
          "1970/01/01" + "  " + data.openTime.end + ":00"
        );
        this.img_list = [
          {
            name: "",
            url: data.logo,
          },
        ];
        if (JSON.stringify(data.salesArea) === '["0-0-0"]') {
          this.is_all_region = 5;
        } else {
          this.is_all_region = 4;
        }
        let useWarehouseNameArr = [];
        for (let i in data.warehouseData) {
          useWarehouseNameArr.push({
            ...data.warehouseData[i],
            id: data.warehouseData[i].warehouseId,
          });
        }
        this.useWarehouseNameArr = useWarehouseNameArr;
        this.region_arr = data.salesArea;
        this.form.openTime.isAllDay = data.openTime.isAllDay === 1;
        //  将字符串转为数组
        this.region = [data.provinceCode, data.cityCode, data.districtCode].map(
          (item) => {
            return parseInt(item);
          }
        );
      },
      // 获取暂存数据
      async getTempShopData() {
        const { data } = await getPauseSave({
          key: this.$route.name,
        });

        if (JSON.stringify(data) === "{}") return;
        this.form = data;
        this.startTime = new Date(
          "1970/01/01" + "  " + data.openTime.start + ":00"
        );
        this.endTime = new Date(
          "1970/01/01" + "  " + data.openTime.end + ":00"
        );
        if (data.logo !== "") {
          this.img_list = [
            {
              name: "",
              url: data.logo,
            },
          ];
        }
        this.useWarehouseNameArr = data.useWarehouseName
          ? data.useWarehouseName.map((item, index) => {
              return {
                warehouseName: item,
                id: parseInt(this.form.warehouseId[index]),
              };
            })
          : [];
        this.is_all_region = data.is_all_region || 4;
        this.region_arr = data.salesArea;
        this.form.openTime.isAllDay = data.openTime.isAllDay === 1;
        //  将字符串转为数组
        this.region = [data.provinceCode, data.cityCode, data.districtCode].map(
          (item) => {
            return parseInt(item);
          }
        );
      },
      // 删除暂存信息
      async delPauseSave(type) {
        const data = delPauseSave({
          key: this.$route.name,
        });

        if (type) {
          this.$message({
            type: "success",
            message: "清除暂存成功",
          });
          this.$closeCurrentGoEdit("/Multistore/AddStore");
        }
      },
      // 暂存数据
      async temData(tempSave) {
        if (this.form.openTime.isAllDay) {
          this.form.openTime.isAllDay = 1;
        }
        const params = {
          ...this.form,
          is_all_region: this.is_all_region,
          area: this.regionName,
          tempSave: tempSave,
          useWarehouseName: this.useWarehouseName,
        };

        this.loading = true;
        const data = await addPauseSave({
          key: this.$route.name,
          data: params,
        });
        this.loading = false;

        this.$message({
          message: "暂存成功",
          type: "success",
        });
        this.$closeCurrentGoEdit("/Multistore/StoreList");
      },
      // 创建商铺 addShop
      async addShop(tempSave) {
        if (!this.form.name.trim() || !this.form.contactName.trim()) {
          this.$message.warning("必填项不能为空");
          return;
        }
        if (this.form.openTime.isAllDay) {
          this.form.openTime.isAllDay = 1;
        }
        this.$refs.form.validate(async (valid) => {
          if (valid) {
            if (!this.form.salesArea.length) {
              this.$message.warning("请选择销售区域");
              return;
            }
            const params = {
              ...this.form,
              area: this.regionName,
              tempSave: tempSave,
            };
            if (this.is_all_region === 5) {
              params.salesArea = ["0-0-0"];
            }

            this.loading = true;
            let target = {};
            if (this.shopId) {
              target = await editShop(this.shopId, {
                ...params,
              });
            } else {
              target = await addShop(params);
            }
            const data = target;
            this.loading = false;

            this.$message({
              message: "提交成功",
              type: "success",
            });
            if (parseInt(this.$store.getters["MUser/enterpriseScope"]) === 5) {
              this.$closeCurrentGoEdit("/Multistore/StoreList");
            } else {
              if (this.systemType === 1) {
                this.$closeCurrentGoEdit(
                  "/SystemSettings/liansuoguanli/ShopList"
                );
              }
            }
          }
        });
      },
    },
  };
</script>
