<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2019-02-19 12:20:38
 * @LastEditors: 无尘
 * @LastEditTime: 2019-02-19 12:20:38
 -->
<template>
  <div class="store-info">
    <div class="info-cell">
      <p class="title">门店信息</p>
      <el-form class="store-info-form info-form" label-width="90px" :rules="rules" ref="storeInfoData" :model="storeInfoData">
        <el-form-item label="门店名称" prop="storeName">
          <!-- <el-input class="w-500" v-model="storeInfoData.storeName">
            <template slot="suffix">
              {{ storeInfoData.storeName ? storeInfoData.storeName.length : 0 }}/20
            </template>
          </el-input> -->
          <limitInput :inputWidth="500" :inputValue.sync="storeInfoData.storeName" :holder="'请输入门店名称'" :maxLength="20"> </limitInput>
        </el-form-item>
        <el-form-item label="所属分组" prop="departmentName">
          <el-input class="w-500" v-model="storeInfoData.groupChainName" @focus="callSelector" :disabled="gicFlag">
            <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="storeInfoData.imageUrls" :limitW="640" :limitH="340" :maxImageLength="10" @uploadOnSuccess="uploadOnSuccess" @sortImg="sortImg" @deleteImage="deleteImage"> </vue-office-upload-image>
          </div>
          <div class="tip font-12 color-909399 m-t-8 line-h-1">门店图片(640*340)，支持.jpg，.jepg，.png类型文件，最多添加10张图片</div>
        </el-form-item>
        <el-form-item label="联系电话" prop="phoneNumber">
          <el-input class="w-500" v-model="storeInfoData.phoneNumber"></el-input>
        </el-form-item>
        <el-form-item label="营业时间" prop="openTime">
          <el-time-select
            placeholder="起始时间"
            v-model="storeInfoData.openTime"
            :picker-options="{
              start: '00:00',
              step: '00:05',
              end: '24:00'
            }"
          >
          </el-time-select>
          ~
          <el-time-select
            placeholder="结束时间"
            v-model="storeInfoData.closeTime"
            :picker-options="{
              start: '00:00',
              step: '00:05',
              end: '24:00',
              minTime: storeInfoData.openTime
            }"
          >
          </el-time-select>
        </el-form-item>
        <el-form-item label="门店类型" prop="storeType">
          <el-radio-group v-model="storeInfoData.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="门店地址" prop="areaId">
          <vue-office-area :areaOptions="areaOptions" @selected="selected" projectName="haoban-web" postUrl="/api-admin/dict-district-list"></vue-office-area>
          <!-- <el-input class="w-500" v-model="storeInfoData.postAddress">
            <template slot="suffix"
              >{{ (storeInfoData.postAddress || '').length }}/50</template
            >
          </el-input> -->
          <limitInput :inputWidth="500" :inputValue.sync="storeInfoData.storeCode" :holder="'请输入门店地址'" :maxLength="50"> </limitInput>
        </el-form-item>
        <el-form-item label="GPS坐标" prop="location">
          <el-input class="w-500 m-r-10" v-model="storeInfoData.location"></el-input>
          <a href="http://m.gpsspg.com/maps.htm" class="a-href" target="_blank">经纬度测试工具</a>
        </el-form-item>
        <el-form-item>
          <template slot="label">
            门店代码
            <!-- <i class="el-icon-question" style="color:#C0C4CC;"></i> -->
          </template>
          <!-- <el-input class="w-500" v-model="storeInfoData.storeCode" :disabled="gicFlag">
            <template slot="suffix"
              >{{ (storeInfoData.storeCode || '').length }}/20</template
            >
          </el-input> -->
          <limitInput :inputWidth="500" :inputValue.sync="storeInfoData.storeCode" :disflag="gicFlag" :holder="'请输入门店代码'" :maxLength="20"> </limitInput>
        </el-form-item>
        <el-form-item label="门店面积"> <el-input class="w-500" v-model="storeInfoData.storeArea" @blur="value => inputBlur(value)"></el-input><span class="font-14 p-l-10">平方米</span> </el-form-item>
      </el-form>
    </div>
    <div class="info-cell">
      <p class="title">店长信息</p>
      <el-form class="store-manager-info-form info-form" label-width="90px" :rules="rules" ref="storeManagerForm" :model="storeInfoData">
        <el-form-item label="店长姓名" prop="managerName">
          <!-- <el-input class="w-500" v-model="storeInfoData.managerName" :disabled="gicFlag">
            <template slot="suffix"
              >{{ (storeInfoData.managerName || '').length }}/10</template
            >
          </el-input> -->
          <limitInput :inputWidth="500" :inputValue.sync="storeInfoData.managerName" :disflag="gicFlag" :holder="'请输入店长姓名'" :maxLength="10"> </limitInput>
        </el-form-item>
        <el-form-item label="手机号码" prop="managerPhone">
          <!-- <el-input v-model="storeInfoData.managerPhone" :disabled="disableFlag || gicFlag"></el-input> -->
          <countryMobile :inputWidth="500" :nationCode.sync="storeInfoData.managerNationcode" v-model="storeInfoData.managerPhone" :holder="'请输入手机号'" :disflag="disableFlag || gicFlag"> </countryMobile>
        </el-form-item>
        <el-form-item label="店长性别">
          <el-radio-group v-model="storeInfoData.managerSex" :disabled="gicFlag">
            <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 class="w-500" v-model="storeInfoData.managerCode" :disabled="gicFlag">
            <template slot="suffix">
              {{ (storeInfoData.managerCode || '').length }}/20
            </template>
          </el-input> -->
          <limitInput :inputWidth="500" :inputValue.sync="storeInfoData.managerCode" :disflag="gicFlag" :holder="'请输入店长代码'" :maxLength="20"> </limitInput>
        </el-form-item>
      </el-form>
    </div>
    <div class="info-cell">
      <p class="title">经营信息</p>
      <el-form class="operate-info-form info-form" label-width="90px" :rules="rules" ref="storeOperateForm" :model="storeInfoData">
        <el-form-item label="特色服务">
          <!-- <el-input class="w-500" type="textarea" :rows="2" v-model="storeInfoData.specialService"></el-input>
          <p class="counter t-rt c-909399">{{ (storeInfoData.specialService || '').length }}/100</p> -->
          <limit-textarea :inputWidth="500" :inputValue.sync="storeInfoData.specialService" :holder="'请输入特色服务'" :getByType="'word'" :maxLength="100"> </limit-textarea>
        </el-form-item>
        <el-form-item label="人均消费">
          <!-- <el-input class="w-500" v-model="storeInfoData.personCost">
            <template slot="suffix">{{ (storeInfoData.personCost + '').length }}/10</template>
          </el-input> -->
          <limitInput :inputWidth="500" :inputValue.sync="storeInfoData.personCost" :holder="'请输入人均消费'" :maxLength="10"> </limitInput>
        </el-form-item>
        <el-form-item label="推荐商品">
          <!--  <el-input class="w-500" type="textarea" :rows="2" v-model="storeInfoData.recommendGoods"></el-input>
          <p class="counter t-rt c-909399">{{ (storeInfoData.recommendGoods || '').length }}/100</p> -->
          <limit-textarea :inputWidth="500" :inputValue.sync="storeInfoData.recommendGoods" :holder="'请输入推荐商品'" :getByType="'word'" :maxLength="100"> </limit-textarea>
        </el-form-item>
        <el-form-item label="品牌介绍">
          <!-- <el-input class="w-500" type="textarea" :rows="2" v-model="storeInfoData.brandDes"></el-input>
          <p class="counter t-rt c-909399">{{ (storeInfoData.recommendGoods || '').length }}/200</p> -->
          <limit-textarea :inputWidth="500" :inputValue.sync="storeInfoData.brandDes" :holder="'请输入品牌介绍'" :getByType="'word'" :maxLength="200"> </limit-textarea>
        </el-form-item>
      </el-form>
    </div>
    <div class="handle-area">
      <el-button type="primary" @click="clickToSave">保 存</el-button>
    </div>
    <vue-select-store ref="storeSelector" :defaultList="defaultList" :currentBrand="currentBrand" :treeSet="treeSet" :selectType="selectType" @handleSelectedList="handleSelectedList"> </vue-select-store
    ><!-- :forbidenList="[storeInfoData.storeGroupId]" -->
  </div>
</template>
<script>
import { postRequest } from '@/api/api';
import vueSelectStore from 'components/common/vueSelectStore';
import countryMobile from '@/components/common/country-mobile.vue';
import PhoneNumber from 'awesome-phonenumber';
import limitInput from '@/components/limit-input.vue';
import limitTextarea from '@/components/limit-textarea.vue';
export default {
  name: 'store-detail',
  components: {
    vueSelectStore,
    countryMobile,
    limitInput,
    limitTextarea
  },
  props: {
    storeInfo: {
      type: Object,
      default() {
        return {};
      }
    },
    gicFlag: {
      type: Boolean,
      default: true
    }
  },
  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)) {
          this.isNew = true;
          return callback(new Error('联系电话格式不正确'));
        } else {
          return callback();
        }*/
        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();
        } */
        let pn = new PhoneNumber('+' + this.storeInfoData.managerNationcode + value);
        if (!pn.isValid() || !pn.isMobile()) {
          callback(new Error('手机号格式不正确'));
        } else {
          callback();
        }
      } else {
        return callback(new Error('请输入手机号码'));
      }
    };
    let validateCode = (rule, value, callback) => {
      if (value) {
        let codeFlag = /^[A-Za-z0-9_\u4e00-\u9fa5]+$/.test(value);
        if (!codeFlag) {
          this.storeInfoData.storeCode = value.replace(/[^A-Za-z0-9_\u4e00-\u9fa5]+/g, '');
        } else {
          return callback();
        }
      } else {
        return callback(new Error('请输入门店代码'));
      }
    };
    let validateMCode = (rule, value, callback) => {
      if (value) {
        let codeFlag = /^[A-Za-z0-9_\u4e00-\u9fa5]+$/.test(value);
        if (!codeFlag) {
          this.storeInfoData.managerCode = value.replace(/[^A-Za-z0-9_\u4e00-\u9fa5]+/g, '');
        } else {
          return callback();
        }
      } else {
        return callback(new Error('请输入店长代码'));
      }
    };
    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();
      }
    };
    let validateHours = (rule, value, callback) => {
      if (value) {
        if (!!this.storeInfo.closeTime) {
          return callback();
        } else {
          return callback(new Error('请选择营业时间'));
        }
      } else {
        return callback(new Error('请选择营业时间'));
      }
    };
    return {
      areaChainName: '',
      location: '',
      areaOptions: {},
      imgs: [],
      uploadUrl: '/haoban-manage-web/upload-img',
      defaultList: [], // 分组回显
      currentBrand: this.storeInfo.storeGroupId, // 传入品牌对应的 groupId
      treeSet: {
        isSelectPerson: false,
        dialogVisible: false,
        isSingle: true, // 是否单选
        groupId: this.storeInfo.brandId,
        openNextBool: true // 展开下级不调用接口
      },
      selectType: 'group',
      disableFlag: false,
      storeInfoData: JSON.parse(JSON.stringify(this.storeInfo)),
      rules: {
        storeName: [{ required: true, message: '请输入门店名称', trigger: 'blur' }],
        departmentName: [{ required: true, message: '请选择所属分组', trigger: 'blur' }],
        groupChainName: [{ required: true, message: '请选择部门', trigger: 'change' }],
        imageUrls: [{ type: 'array', required: true, message: '请选择门店图片', trigger: 'change' }],
        areaId: [{ required: true, message: '请选择门店地址', trigger: 'blur' }],
        storeType: [{ required: true, message: '请选择门店类型', trigger: 'blur' }],
        openTime: [{ required: true, validator: validateHours, trigger: 'blur' }],
        location: [{ required: true, message: '请选择经纬度', trigger: 'blur' }],
        phoneNumber: [{ required: true, validator: validatePhone, trigger: 'blur' }],
        storeCode: [{ required: true, validator: validateCode, trigger: 'blur' }],
        managerName: [{ required: true, message: '请输入店长姓名', trigger: 'blur' }],
        managerPhone: [{ required: true, validator: validateCellPhone, trigger: 'blur' }],
        managerCode: [{ required: true, validator: validateMCode, trigger: 'blur' }],
        specialService: [{ max: 20, message: '长度在 20 个字符以内', trigger: 'blur' }],
        personCost: [{ validator: validateMoney, trigger: 'blur' }]
      }
    };
  },
  methods: {
    inputBlur: function(val) {
      let that = this;
      if (!that.storeInfoData.storeArea) {
        that.storeInfoData.storeArea = '';
      }
      that.storeInfoData.storeArea = !!Number(that.storeInfoData.storeArea.replace(/[^\d.]/g, '')) ? that.storeInfoData.storeArea.replace(/[^\d+(.\d+)]/g, '') : '';
      that.storeInfoData.storeArea = Number(that.storeInfoData.storeArea).toFixed(2);
      if (that.storeInfoData.storeArea >= 999999) {
        that.storeInfoData.storeArea = Number(999999).toFixed(2);
      }
    },

    callSelector() {
      this.treeSet = {
        isSelectPerson: false,
        dialogVisible: true,
        isSingle: true, // 是否单选
        groupId: this.storeInfoData.brandId,
        openNextBool: true // 展开下级不调用接口
      };
    },

    handleSelectedList(list) {
      this.storeInfoData.groupChainName = !!list.length ? list[0].chainName : '';
      this.storeInfoData.departmentName = !!list.length ? list[0].label : '';
      this.storeInfoData.storeGroupId = !!list.length ? list[0].id : '';
    },

    selected(val) {
      let that = this;
      that.areaChainName = val.provinceName + '/' + val.cityName + '/' + val.countryName;
    },

    uploadOnSuccess(res, list) {
      res.file.url = res.res.result[0].qcloudImageUrl;
      list.push(res.file);
    },

    /* eslint-disable */
    sortImg(val) {
      this.storeInfoData.imageUrls = val;
    },
    deleteImage(i) {
      this.storeInfoData.imageUrls.splice(i, 1);
    },

    async clickToSave() {
      let that = this;
      let p1 = new Promise(function(resolve, reject) {
        that.$refs['storeInfoData'].validate(valid => {
          if (valid) {
            resolve();
          }
        });
      });
      let p2 = new Promise(function(resolve, reject) {
        that.$refs['storeManagerForm'].validate(valid => {
          if (valid) {
            resolve();
          }
        });
      });
      let p3 = new Promise(function(resolve, reject) {
        that.$refs['storeOperateForm'].validate(valid => {
          if (valid) {
            resolve();
          }
        });
      });
      Promise.all([p1, p2, p3]).then(function() {
        that.save();
      });
    },
    save() {
      let that = this;
      let locationArr = that.location.split(',');
      // 将门店经纬度信息拆分成两个字段
      that.storeInfoData.longitude = locationArr[1];
      that.storeInfoData.latitude = locationArr.length !== 2 ? '' : locationArr[0];
      that.storeInfoData.managerPhone = that.storeInfoData.managerPhone;
      that.storeInfoData.areaChainName = that.areaOptions.provinceName + '/' + that.areaOptions.cityName + '/' + that.areaOptions.countryName;
      let params = JSON.parse(JSON.stringify(that.storeInfoData));
      let imageUrls = [];
      that.storeInfoData.imageUrls.forEach(img => {
        imageUrls.push(img.url);
      });
      params.imageUrls = imageUrls.join(',');
      postRequest('/haoban-manage-web/store/update', params)
        .then(res => {
          if (res.data.errorCode == 1) {
            that.$message.success({
              message: '操作成功！'
            });
          } else {
            that.$message.error({
              message: res.data.message
            });
          }
        })
        .catch(e => {
          that.$message.error({
            message: e.message
          });
        });
    },
    formatStoreInfo(obj) {
      let that = this;
      that.defaultList = [
        {
          id: obj.storeGroupId,
          label: obj.departmentName
        }
      ];
      if(!obj.managerNationcode) {
        obj.managerNationcode = '86';
      }
      let arr = (obj.areaChainName || '').split('/');
      // 将门店地址信息的省市区地址拆分
      that.areaOptions = {
        provinceName: arr[0],
        provinceId: obj.provinceId,
        cityName: arr[1],
        cityId: obj.cityId,
        countryName: arr[2],
        countyId: obj.countyId
      };
      that.imgs = !obj.imageUrl ? [] : obj.imageUrl.split(',');
      let newImgs = [];
      that.imgs.forEach(img => {
        newImgs.push({ url: img });
      });
      // that.imgs = newImgs;
      obj.imageUrls = newImgs;
      obj.location = !!obj.longitude ? obj.latitude + ',' + obj.longitude : '';
      that.location = !!obj.longitude ? obj.latitude + ',' + obj.longitude : '';
      that.disableFlag = !!obj.managerPhone? true : false;
    }
  },
  watch: {
    storeInfo: function(newData) {
      this.treeSet.groupId = newData.brandId;
      this.storeInfoData = newData;
      this.formatStoreInfo(this.storeInfoData);
    }
  },
  beforeMount() {
    this.treeSet.groupId = this.storeInfo.brandId;
  },
  mounted() {
    this.storeInfoData = JSON.parse(JSON.stringify(this.storeInfo));
    this.formatStoreInfo(this.storeInfoData);
  }
};
</script>
<style lang="scss">

</style>
