<!--
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2023-05-26 16:37:34
 * @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @LastEditTime: 2024-02-22 16:21:34
 * @FilePath: \admin-manage\src\views\operationManage\shopManage\shopAdd.vue
 * @Description: 
 * 
 * Copyright (c) 2023 by ${git_name_email}, All Rights Reserved. 
-->
<template>
  <div class="shopAdd app-container" v-loading="loading">
    <el-form
      :model="setQuery"
      ref="setQuery"
      :rules="rules"
      v-loading="pageLoading"
      :disabled="disabled"
      label-width="130px"
    >
    <el-form-item label="主体名称：" prop="shopMainId">
        <el-select v-model="setQuery.shopMainId" size="small" filterable class="item-width-300" placeholder="请搜索选择店铺主体">
          <el-option
            v-for="item in shopMainOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="店铺名称：" prop="shopName">
        <el-input
          v-model.number="setQuery.shopName"
          size="small"
          :maxlength="18"
          class="item-width-300"
        ></el-input>
      </el-form-item>
      <el-form-item label="店铺地址：" prop="address">
         <el-input
         disabled
            v-model="setQuery.address"
            class="item-width-500"
            size="small"
            placeholder="请点击右侧定位图标选择店铺地址" 
          ></el-input>
          <i class="el-icon-location ml10 position red" @click="chooseAddress"></i>
      </el-form-item>
       <el-form-item label="店铺类型：" prop="shopType">
        <el-select v-model="setQuery.shopType" size="small" class="item-width-300" placeholder="请选择店铺经营类型">
          <el-option
            v-for="item in options1"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="店铺经营类型：" prop="shopMenuId">
        <el-select v-model="setQuery.shopMenuId" size="small" class="item-width-300" placeholder="请选择店铺经营类型">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="店铺头像：" prop="logoPath">
        <Upload
          type="logoPath"
          id="logoPath"
          width="250px"
          height="150px"
          :disabled="mode == 'detail'"
          uploadType="SHOP_INFO"
          :imgUrl="setQuery.logoPath"
          @uploadEnd="uploadEnd"
        ></Upload>
      </el-form-item>
      <el-form-item label="店铺门头图片：" prop="doorImg">
        <Upload
          type="doorImg"
          id="doorImg"
          width="250px"
          height="150px"
          :disabled="mode == 'detail'"
          uploadType="SHOP_INFO"
          :imgUrl="setQuery.doorImg"
          @uploadEnd="uploadEnd"
        ></Upload>
      </el-form-item>

      <el-form-item label="店铺简介：">
        <el-input
          type="textarea"
          placeholder="请输入店铺简介"
          v-model="setQuery.detailContent"
          maxlength="400"
          class="item-width-500"
          show-word-limit
        >
        </el-input>
      </el-form-item>
      
   
    </el-form>

    <el-dialog title="选择地址" close="chose-model" :close-on-press-escape="false" :show-close="false" :close-on-click-modal="false" width="60vw" :visible.sync="showMap">
      <div id="container"></div>
      <div class="address-input-box">
        <el-input
              v-model="setQuery.address"
              size="small"
              class="address-input"
              placeholder="请先点击地图定位，再修改详细地址"
            ></el-input>
        <el-button type="primary" size="small" class="address-btn"  @click="saveAddress">提 交</el-button>
      </div>
    </el-dialog>


  <!-- 新增和编辑模式 -->
    <div class="btn-group" v-if="mode == 'add'|| mode == 'edit'">
      <el-button>取 消</el-button>
      <el-button type="primary" :loading="loading" @click="save"
        >提交</el-button >
    </div>
    <!-- 详情时的按钮 -->
    <div class="btn-group" v-else>
      <el-button>取 消</el-button>
      <el-button type="primary" :loading="loading" @click="edit"
        >编辑</el-button >
    </div>
    

  </div>
</template>

<script>
import Upload from "@/components/Upload";
import { add, detail, update,getMainName } from "@/api/shop";
import {getMenuName} from '@/api/appConfig';
import {getRuleList} from '@/api/commission'
import { debounce } from "@/utils/index";
export default {
  components: {
    Upload,
  },
  data() {
    return {
      map:null,
      mode:'detail',//编辑模式
      showMap:false,
      setQuery: {
        address: "",
        businessImg: "",
        city: "",
        detailImg: "",
        district: "",
        doorImg: "",
        handlerImg: "",
        idCardBack: "",
        idCardFront: "",
        idCardNo: "",
        logoPath: "",
        mapLat: "",
        mapLon: "",
        province: "",
        serviceName: "",
        serviceTel: "",
        shopLabel: "",
        shopMainId: "",
        shopName: "",
        shopType: '',
        source:'2',
        shareChannelId:''
      },
      ruleOptions:[],
      options:[],
      options1:[
         {
          value: 1,
          label: "小微商户",
        },
        {
          value: 2,
          label: "个体工商户",
        },
        {
          value: 3,
          label: "企业",
        },
        {
          value: 4,
          label: "机关事业单位或社会团体",
        },
      ],
      shopMainOptions:[],//主体选择
      disabled: false,
      pageLoading: false, //页面loading
      loading: false,
      rules: {
        shopMainId: [
          { required: true, message: "请选择商铺主体", trigger: "change" },
        ],
        shopMenuId: [
          { required: true, message: "请选择商铺经营类型", trigger: "change" },
        ],
        shopType: [
          { required: true, message: "请选择商铺类型", trigger: "change" },
        ],
         shopName: [
          { required: true, message: "请输入商铺名称", trigger: "blur" },
        ],
        address: [
          { required: true, message: "请输入商铺地址", trigger: "blur" },
        ],
        shareChannelId: [
          { required: true, message: "请选择商家佣金", trigger: "change" },
        ],
        logoPath: [
          { required: true, message: "请上传店铺头像", trigger: "change" },
        ],
        doorImg: [
          { required: true, message: "请上传门头照", trigger: "change" },
        ],
        detailImg: [
          { required: true, message: "请上传店铺详情图", trigger: "change" },
        ],
        businessImg: [
          { required: true, message: "请上传营业执照", trigger: "change" },
        ],
        serviceName: [
          { required: true, message: "请输入联系人", trigger: "blur" },
        ],
        serviceTel: [
          { required: true, message: "请输入客服电话", trigger: "blur" },
        ],
        idCardBack: [
          {
            required: true,
            message: "请上传法人身份证反面照",
            trigger: "change",
          },
        ],
        idCardFront: [
          {
            required: true,
            message: "请上传法人身份证正面照",
            trigger: "change",
          },
        ],
        handlerImg: [
          {
            required: true,
            message: "请上传法人手持身份证照",
            trigger: "change",
          },
        ],
      },
    };
  },
  watch: {
    'setQuery.address':debounce(function(val){
      if(this.map){
        let that = this
        //创建地址解析器实例
        var myGeo = new BMapGL.Geocoder();
            that.marker? that.map.removeOverlay(that.marker):''
        // 将地址解析结果显示在地图上，并调整地图视野
        myGeo.getPoint(val, function(point){
            if(point ){
              console.log(point);
              that.setQuery.mapLat = point.lat
              that.setQuery.mapLon = point.lng
               that.marker = new BMapGL.Marker(point, {title: val})
               if(that.map){
                 that.map.centerAndZoom(point, 16);
                 that.map.addOverlay(that.marker)
               }
            }
        }, that.setQuery.city)
      }
    })
  },
  methods: {
    edit(){
          this.$router.push({
            path: "/operationManage/shopManage/shopAdd",
            query: {
              title: "店铺编辑",
              id:this.$route.query.id,
            },
          });
    },
    save() {
      this.$refs.setQuery.validate((v) => {
        if (v) {
          if(this.loading) return
          if (this.setQuery.shopId) {
            this.update();
          } else {
            this.add();
          }
        }
      });
    },
    add() {
      this.loading = true;
      add(this.setQuery).then((res) => {
        this.loading = false;
        if (res.state == "Success") {
          this.$notify({
            title: "成功",
            message: "操作成功",
            type: "success",
          });
          
          this.$router.push("/operationManage/shopManage/index");
        }
      });
    },
    update() {
      this.loading = true;
      update(this.setQuery).then((res) => {
        this.loading = false;
        if (res.state == "Success") {
          this.$notify({
            title: "成功",
            message: "操作成功",
            type: "success",
          });
          
          this.$router.push("/operationManage/shopManage/index");
        }
      });
    },
    // 图片统一上传
    uploadEnd(val) {
      this.setQuery[val.type] = val.url;
    },
    detail() {
      this.pageLoading = true;
      detail({ shopId: this.$route.query.id }).then((res) => {
        this.pageLoading = false;
        if (res.state == "Success") {
          this.setQuery = res.content;
        }
      });
    },
    // 获取经营类型
    getMenuName(){
      getMenuName().then(res=>{
        if(res.state == 'Success'){
          for (const key in res.content) {
            if (res.content.hasOwnProperty.call(res.content, key)) {
                this.options.push({
                  label:res.content[key],
                  value:Number(key) 
                })              
            }
          }
          
        }
      })
    },
    // 获取主体类型
    getMainName(){
      getMainName().then(res=>{
        if(res.state == 'Success'){
          for (const key in res.content) {
            if (Object.hasOwnProperty.call(res.content, key)) {
              this.shopMainOptions.push({
                label:res.content[key],
                value:key
              })
            }
          }
        } 
      })
    },
    // 选择经营地址
    chooseAddress() {
      if(this.mode == 'detail') return
      this.showMap = true;
      let that = this
      
      this.$nextTick(() => {
        this.map = new BMapGL.Map("container");
        var geoc = new BMapGL.Geocoder();
        that.map.enableScrollWheelZoom(); // 启用滚轮放大缩小
        var myCity = new BMapGL.LocalCity();
        myCity.get((result)=> {
          console.log(result);
          var cityName = result.name;
          that.map.setCenter(cityName);
          var point = new BMapGL.Point(result.center.lat, result.center.lng);
          that.map.centerAndZoom(point, 15);
          let cache = this.setQuery.address
          this.setQuery.address = '切换地址触发标记点'
          setTimeout(() => {
            this.setQuery.address = cache
          }, 100);

        });
       
        that.map.addEventListener("click", function (e) {
          console.log(1111111,e.latlng);
          var pt = e.latlng;
          that.map.removeOverlay(that.marker); //移除点标记
          geoc.getLocation(pt, function (rs) {
            var addComp = rs.addressComponents;
            let point1 = new BMapGL.Point(rs.point.lng, rs.point.lat);
            that.marker = new BMapGL.Marker(point1); // 创建标注
            that.map.addOverlay(that.marker); // 将标注添加到地图中
            that.setQuery.address = rs.address +rs.content.poi_desc
            // 选择营业地址时保存省市区
            that.setQuery.province = addComp.province
            that.setQuery.city = addComp.city
            that.setQuery.district = addComp.district
            that.setQuery.mapLat = rs.point.lat
            that.setQuery.mapLon = rs.point.lng
            console.log(rs);
          });
        });
        

      });
    },
    // 保存地址
    saveAddress(){
        this.$confirm('请确认地址信息准确无误，并精确到门牌号?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.showMap = false
        })
    },
    getRuleList(){
      getRuleList().then(res=>{
        if(res.state == 'Success'){
          console.log(res.content.records);
          this.ruleOptions = res.content.records.filter(item=>item.shareType == 2)
          // for (const key in res.content) {
          //   if (Object.hasOwnProperty.call(res.content, key)) {
          //     this.shopMainOptions.push({
          //       label:res.content[key],
          //       value:key
          //     })
          //   }
          // }
        } 
      })
    }
  },
  created() {
    this.getRuleList()
    this.getMenuName()
    this.getMainName()
    if (this.$route.query.title == "店铺编辑") {
      this.disabled = false;
      this.mode = 'edit'
      this.detail();
    } else if (this.$route.query.title == "店铺详情") {
      this.disabled = true;
      this.mode = 'detail'
      this.detail();
    } else {
      this.disabled = false;
      this.mode = 'add'
    }
  },
};
</script>

<style lang="scss" scoped>
.shopAdd {
  padding-bottom: 40px;
  .position{
    cursor: pointer;
    font-size: 20px;
  }
  .btn-group {
    display: flex;
    align-items: center;
    justify-content: center;
  }
  #container {
    width: 100%;
    height: 600px;
  }
}
</style>