<template>
  <div class="common-set-wrap">
    <nav-crumb :navpath="navpath"></nav-crumb>
    <div class="right-content">
      <div class="right-box">
        <div>
          <div class="store-info">
            <div class="info-cell">
              <p class="title">门店信息</p>
              <el-form :rules="rules" :model="storeInfo" ref="storeInfo" class="store-info-form info-form" label-width="100px">
                <el-form-item label="门店名称" prop="storeName">
                  <el-input v-model="storeInfo.storeName">
                    <template slot="suffix">{{storeInfo.storeName ? storeInfo.storeName.length : 0}}/20</template>
                  </el-input>
                </el-form-item>
                <el-form-item label="所属分组" prop="departmentName">
                  <el-input v-model="storeInfo.departmentName" @focus="callSelector">
                    <i slot="suffix" class="el-input__icon el-icon-arrow-down"></i>
                  </el-input>
                </el-form-item>
                <el-form-item label="门店图片(640*340)" prop="imageUrls">
                  <div class="member-upload-image">
                        <vue-office-upload-image
                            projectName="haoban-manage-web"
                            wxFlag="0"
                            :actionUrl="uploadUrl"
                            :imageList="imgs"
                            :limitW="640"
                            :limitH="340"
                            :maxImageLength="5"
                            @uploadOnSuccess="uploadOnSuccess"
                            @sortImg="sortImg"
                            @deleteImage="deleteImage">
                        </vue-office-upload-image>
                  </div>
                </el-form-item>
                <el-form-item label="联系电话" prop="phoneNumber">
                  <el-input v-model="storeInfo.phoneNumber"></el-input>
                </el-form-item>
                <el-form-item label="营业时间" prop="phoneNumber">
                  <el-time-select placeholder="起始时间" v-model="storeInfo.openTime" :picker-options="{
                                  start: '00:00',
                                  step: '00:05',
                                  end: '24:00'
                              }">
                  </el-time-select>
                  ~
                  <el-time-select placeholder="结束时间" v-model="storeInfo.closeTime" :picker-options="{
                                  start: '00:00',
                                  step: '00:05',
                                  end: '24:00',
                                  minTime: storeInfo.openTime
                              }">
                  </el-time-select>
                </el-form-item>
                <el-form-item label="门店类型">
                  <el-radio-group v-model="storeInfo.storeType">
                    <el-radio :label="0">自营</el-radio>
                    <el-radio :label="1">联营</el-radio>
                    <el-radio :label="2">代理</el-radio>
                    <el-radio :label="3">代销</el-radio>
                    <el-radio :label="4">托管</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="门店地址">
                  <vue-office-area :areaOptions="areaOptions" @selected="selected" projectName="haoban-web" postUrl="/haoban-manage-web/dict-district-list"></vue-office-area>
                  <el-input v-model="storeInfo.postAddress">
                    <template slot="suffix">{{(storeInfo.postAddress || "").length}}/50</template>
                  </el-input>
                </el-form-item>
                <el-form-item label="GPS坐标">
                  <el-input v-model="location" class="m-r-10"></el-input>
                  <a href="http://m.gpsspg.com/maps.htm" class="a-href" target="_blank">经纬度测试工具</a>
                </el-form-item>
                <el-form-item prop="storeCode">
                  <template slot="label">
                    门店代码
                    <i class="el-icon-question" style="color:#C0C4CC;"></i>
                  </template>
                  <el-input v-model="storeInfo.storeCode">
                    <template slot="suffix">{{(storeInfo.storeCode || "").length}}/20</template>
                  </el-input>
                </el-form-item>
              </el-form>
            </div>
            <div class="info-cell">
              <p class="title">店长信息</p>
              <el-form ref="storeManager" :rules="rules" :model="storeInfo" class="store-manager-info-form info-form" label-width="100px">
                <el-form-item label="店长姓名" prop="managerName">
                  <el-input v-model="storeInfo.managerName">
                    <template slot="suffix">{{(storeInfo.managerName || "").length}}/10</template>
                  </el-input>
                </el-form-item>
                <el-form-item label="手机号码" prop="managerPhoneNumber">
                  <el-input v-model="storeInfo.managerPhoneNumber" :disabled="!isNew && !!storeInfo.managerPhoneNumber"></el-input>
                </el-form-item>
                <el-form-item label="店长性别">
                  <el-radio-group v-model="storeInfo.managerSex">
                    <el-radio :label="1">男</el-radio>
                    <el-radio :label="2">女</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="店长代码" prop="managerCode">
                  <el-input v-model="storeInfo.managerCode">
                    <template slot="suffix">{{(storeInfo.managerCode || "").length}}/20</template>
                  </el-input>
                </el-form-item>
              </el-form>
            </div>
            <div class="info-cell">
              <p class="title">经营信息</p>
              <el-form ref="storeOperate" :rules="rules" :model="storeInfo" class="operate-info-form info-form" label-width="90px">
                <el-form-item label="特色服务" prop="specialService">
                  <el-input type="textarea" :rows="2" v-model="storeInfo.specialService"></el-input>
                  <p class="counter t-rt c-909399">{{(storeInfo.specialService || "").length}}/20</p>
                </el-form-item>
                <el-form-item label="人均消费" prop="personCost">
                  <el-input v-model="storeInfo.personCost">
                    <template slot="suffix">{{(storeInfo.personCost+'').length}}/10</template>
                  </el-input>
                </el-form-item>
                <el-form-item label="推荐商品">
                  <el-input type="textarea" :rows="2" v-model="storeInfo.recommendGoods"></el-input>
                  <p class="counter t-rt c-909399">{{(storeInfo.recommendGoods || "").length}}/100</p>
                </el-form-item>
                <el-form-item label="品牌介绍">
                  <el-input type="textarea" :rows="2" v-model="storeInfo.brandDes"></el-input>
                  <p class="counter t-rt c-909399">{{(storeInfo.recommendGoods || "").length}}/200</p>
                </el-form-item>
              </el-form>
            </div>
            <div class="handle-area">
              <el-button type="primary" @click="clickToSave">保存</el-button>
            </div>
          </div>
          <vue-select-store ref="storeSelector" @handleSelectedList="handleSelectedList" :treeSet="treeSet" selectType="group" :forbidenList="[storeInfo.storeGroupId]"></vue-select-store>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import navCrumb from '@/components/nav/nav.vue';
import { getRequest, postRequest, postJsonRequest } from '@/api/api';
import vueSelectStore from "components/common/vueSelectStore";
export default {
  name: "store-info",
  components: {
    navCrumb,
    vueSelectStore
  },
  data() {
    let validatePhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入联系电话'));
      } else {
        let reg = /^1[34578]\d{9}$/;
        let regPhone = /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}$/;
        if (!reg.test(value) && !regPhone.test(value)) {
          return callback(new Error("联系电话格式不正确"));
        } else {
          return callback();
        }
      }
    }
    let validateCellPhone = (rule, value, callback) => {
      if (value) {
        let reg = /^1[34578]\d{9}$/;
        if (!reg.test(value)) {
          return callback(new Error("手机号码格式不正确"));
        } else {
          return callback();
        }
      } else {
        return callback();
      }
    }
    let validateMoney = (rule, value, callback) => {
      if (value) {
        let reg = /^\d+(\.\d+)?$/;
        if (!reg.test(value * 1)) {
          return callback(new Error("人均消费只能为非负整数或者小数"));
        } else {
          return callback();
        }
      } else {
        return callback();
      }
    }
    return {
      // 面包屑参数
      navpath: [{
          name: '首页',
          path: '/index'
        },
        {
          name: '企业通讯录',
          path: '/administrativeFrame'
        },
        {
          name: '门店架构',
          path: '/storeFrame'
        },
        {
          name: '编辑门店',
          path: ''
        }
      ],
      treeSet: {
          isSelectPerson: false,
          dialogVisible: false,
          isSingle: true // 是否单选
      },
      storeInfo: {
        groupChainName: ""
      },
      areaChainName: "",
      location: "",
      areaOptions: {},
      imgs: [],
      uploadUrl: "/haoban-manage-web/upload-img",
      rules: {
        storeName: [
          { required: true, message: '请输入门店名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        groupChainName: [
          { required: true, message: '请选择部门', trigger: 'change' }
        ],
        phoneNumber: [{ required: true, validator: validatePhone, trigger: "blur" }],
        storeCode: [
          { required: true, message: '请输入门店代码', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        managerName: [
          { required: true, message: '请输入店长姓名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        managerPhoneNumber: [{ required: true, validator: validateCellPhone, trigger: "blur" }],
        managerCode: [
          { max: 20, message: '长度在 20 个字符以内', trigger: 'blur' }
        ],
        specialService: [{ max: 20, message: '长度在 20 个字符以内', trigger: 'blur' }],
        personCost: [{ validator: validateMoney, trigger: "blur" }]
      }
    };
  },
  methods: {
    callSelector() {
      this.treeSet.dialogVisible = true;
    },
    handleSelectedList(list) {
      this.storeInfo.departmentName = list[0].label;
      this.storeInfo.storeGroupId = list[0].id;
    },
    selected(val) {
      let that = this;
      that.areaChainName = val.provinceName + "/" + val.cityName + "/" + val.countryName;
    },
    getStoreInfo() {
      let that = this;
      let params = { storeId: that.$route.query.storeId };
      getRequest("/haoban-manage-web/store/findStoreById", params)
        .then(res => {
          if (res.data.errorCode == 1) {
            that.showEmployee = "store";
            that.formatStoreInfo(res.data.result);
          } else {
            that.$message.error({
              message: res.data.message
            });
          }
        });
    },
    clickToSave() {
      let ths = this
      let p1 = new Promise(function(resolve, reject) {
        ths.$refs["storeInfo"].validate((valid) => {
          if (valid) {
            resolve();
          }
        })
      });
      let p2 = new Promise(function(resolve, reject) {
        ths.$refs["storeManager"].validate((valid) => {
          if (valid) {
            resolve();
          }
        });
      });
      let p3 = new Promise(function(resolve, reject) {
        ths.$refs["storeOperate"].validate((valid) => {
          if (valid) {
            resolve();
          }
        })
      });
      Promise.all([p1, p2, p3]).then(function() {
        ths.save();
      });
    },
    formatStoreInfo(obj) {
      let ths = this;
      let arr = (obj.areaChainName || "").split("/");
      ths.areaOptions = {
        provinceName: arr[0],
        provinceId: obj.provinceId,
        cityName: arr[1],
        cityId: obj.cityId,
        countryName: arr[2],
        countyId: obj.countyId
      };
      ths.imgs = !obj.imageUrl ? [] : obj.imageUrl.split(",");
      let newImgs = [];
      ths.imgs.forEach(img => {
          newImgs.push({ url: img });
      });
      ths.imgs = newImgs;
      ths.storeInfo = obj;
    },
    uploadOnSuccess(res, list) {
        console.log(res);
        res.file.url = res.res.result[0].qcloudImageUrl;
        list.push(res.file);
    },
    sortImg() {},
    deleteImage() {},
    save() {
      let that = this;
      let locationArr = that.location.split(",");
      that.storeInfo.longitude = locationArr[0];
      that.storeInfo.latitude = locationArr.length !== 2 ? "" : locationArr[1];
      that.storeInfo.managerPhone = that.storeInfo.managerPhoneNumber;
      that.storeInfo.areaChainName = that.areaChainName;
      let params = that.storeInfo;
      let imageUrls = [];
      that.imgs.forEach(img => {
          imageUrls.push(img.url);
      })
      params.imageUrls = imageUrls.join(",");
      let url = that.isNew ? "/haoban-manage-web/store/insert" : "/haoban-manage-web/store/update";
      getRequest(url, params)
        .then(res => {
          if (res.data.errorCode == 1) {
            that.$message.success({
              message: res.data.message
            });
            window.history.go(-1);
          } else {
            that.$message.error({
              message: res.data.message
            });
          }
        })
        .catch(e => {
          that.$message.error({
            message: e.message
          });
        });
    }

  },
  computed: {
    isNew() {
      if (this.$route.query.storeId) {
        return false;
      } else {
        return true;
      }
    }
  },
  beforeMount() {
    if (!this.isNew) {
      this.getStoreInfo();
    }
  }
}

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