<!--
 * @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: wenjie 1454560336@qq.com
 * @LastEditTime: 2024-09-03 13:58:11
 * @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-tabs v-model="activeName">
    <el-tab-pane label="基本信息" name="1">
      <el-form-item label="商铺主体：" prop="shopMainId">
        <el-select v-model="setQuery.shopMainId" :disabled="mode != 'add'" 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="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-cascader
         size="small"
         class="item-width-300"
         placeholder="请选择店铺经营类型"
         v-model="setQuery.shopMenuId"
        :options="options"
        :props="{
          value:'id',
          label:'menuName',
          children:'child',
        }"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="店铺名称：" prop="shopName">
        <el-input
          v-model="setQuery.shopName"
          size="small"
          class="item-width-300"
        ></el-input>
      </el-form-item>
       <!-- <el-form-item label="店铺标签：">
        <el-input
          v-model="setQuery.shopLabel"
          size="small"
          class="item-width-300"
        ></el-input>
      </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="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="regionCode">
        <el-input
          placeholder="请输入区域"
          v-model="setQuery.regionCode"
          class="item-width-500"
        >
        </el-input>
      </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-item label="店铺电话：" prop="serviceTel">
        <el-input
          type="tel"
          placeholder="请输入店铺电话"
          v-model="setQuery.serviceTel"
          class="item-width-300"
        >
        </el-input>
      </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="detailImg">
        <Upload
          type="detailImg"
          id="detailImg"
          width="250px"
          height="150px"
          :disabled="mode == 'detail'"
          uploadType="SHOP_INFO"
          :imgUrl="setQuery.detailImg"
          @uploadEnd="uploadEnd"
        ></Upload>
      </el-form-item>

       <!-- <el-form-item label="店铺状态：">
        <el-radio-group v-model="setQuery.doorImg">
            <el-radio :label="1">关闭</el-radio>
            <el-radio :label="2">运营中</el-radio>
          </el-radio-group>
      </el-form-item> -->
    </el-tab-pane>
    <el-tab-pane label="其他信息" name="2">
        <el-form-item label="经营商品类型：" prop="serviceCode">
        <el-checkbox-group v-model="setQuery.serviceCode">
          <el-checkbox label="801">研学商品</el-checkbox>
          <el-checkbox label="802">虚拟商品充值</el-checkbox>
          <el-checkbox label="803">餐饮商品</el-checkbox>
          <el-checkbox label="809">贵大商品</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
        <el-form-item label="经营商品分类：" prop="serviceCate">

       <el-cascader
        v-model="setQuery.serviceCate"
        :options="typeOptions"
        :props="{
          multiple: true,
          value:'id',
          label:'cateName',
          children:'child'
        }"
        @change=""></el-cascader>
      </el-form-item>
      <el-form-item label="银联分账帐户：">
        <el-select v-model="setQuery.authAccount" size="small" filterable class="item-width-300" placeholder="请搜索选择店铺主体">
          <el-option
            v-for="(item,index) in authOptions"
            :key="index"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="分账规则：" prop="shareId">
            <el-select
              v-model="setQuery.shareId"
              class="item-width-300"
              placeholder="请选择分账规则"
            >
              <el-option
                v-for="item in ruleOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        <el-form-item label="店铺搜索：">

       <el-radio-group v-model="setQuery.searchEnable">
        <el-radio :label="1">可搜索</el-radio>
        <el-radio :label="2">不可搜索</el-radio>
      </el-radio-group>
      </el-form-item>

       <el-form-item label="店铺状态：" >

       <el-radio-group :disabled="!setQuery.authAccount" v-model="setQuery.state">
        <el-radio :label="1">运营中</el-radio>
        <el-radio :label="2">关闭</el-radio>
      </el-radio-group>
      </el-form-item>
      <el-form-item label="绑定主商户" prop="platformType">
          <el-checkbox-group v-model="setQuery.platformType">
            <el-checkbox label="1">慧研学惠生活</el-checkbox>
            <el-checkbox label="2" >印象贵大</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

    </el-tab-pane>

  </el-tabs>



    </el-form>

    <el-dialog title="选择地址" close="chose-model" :close-on-press-escape="false" :close-on-click-modal="false" width="60vw" :visible.sync="showMap">
      <div id="container"></div>
        <el-form
          :model="setQuery"
          ref="address"
          :rules="rules1"
        >
        <el-form-item label="" prop="address">
          <div class="address-input-box">
            <el-select v-model="setQuery.address" :loading="addressLoading" filterable remote :remote-method="searchAddress" @change="selectAddress" class="address-input" placeholder="请选择输入地址或者点击地图">
              <el-option
                v-for="item in addressOptions"
                :key="item.label+item.value"
                :label="item.label+'  '+item.value"
                :value="item.value">
                <span style="color: #222; font-size: 13px">{{ item.label }}</span>
                  <span style="margin-left:10px; color: #8492a6; font-size: 13px">{{ item.value }}</span>
              </el-option>
            </el-select>
              <!-- <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-form-item>
        </el-form>
    </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 {getMenuData} from '@/api/appConfig';
import {getRuleList} from '@/api/rule'
import {getData} from '@/api/goods'
import {finishComplexList} from '@/api/payment'
import {getSearchList,uidToAddress} from '@/api/common'
import { debounce } from "@/utils/index";
export default {
  components: {
    Upload,
  },
  data() {
    var validateTel = (rule, value, callback) => {
        if (value == '') {
          callback(new Error('请输入店铺电话'));
        } else {
          let reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
          if (reg.test(value)) {
            callback();
          }else{
            callback(new Error('请输入正确的手机号'));
          }
        }
      };
    return {
      checkList:[],
      activeName:"1",
      map:null,
      mode:'detail',//编辑模式
      showMap:false,
      cityName:'',
      addressLoading:false,
      setQuery: {
        regionCode:'',
        address: "",
        businessImg: "",
        city: "",
        detailImg: "",
        district: "",
        doorImg: "",
        idCardNo: "",
        logoPath: "",
        mapLat: "",
        mapLon: "",
        province: "",
        serviceName: "",
        serviceTel: "",
        shopLabel: "",
        shopMainId: "",
        shopName: "",
        shopType: '',
        source:'2',
        shareId:'',
        shareChannelId:'',
        serviceCode:[],//经营类型
        serviceCate:[],//商品分类
        authAccount:"",
        searchEnable:1,
        state:2,
        platformType:[]
      },
      authOptions:[],//银联账号
      typeOptions:[],//商品分类
      ruleOptions:[],
      options:[],
      addressOptions:[],
      options1:[
         {
          value: 1,
          label: "小微商户",
        },
        {
          value: 2,
          label: "个体工商户",
        },
        {
          value: 3,
          label: "企业",
        },
        {
          value: 4,
          label: "机关事业单位或社会团体",
        },
      ],
      shopMainOptions:[],//主体选择
      disabled: false,
      pageLoading: false, //页面loading
      loading: false,
      rules: {
         regionCode: [
          { required: true, message: "请输入区域", trigger: "blur" },
        ],
        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" },
        ],
        shareId: [
          { required: true, message: "请选择分账规则", trigger: "change" },
        ],
        detailImg: [
          { required: true, message: "请上传店铺详情图", trigger: "change" },
        ],
        businessImg: [
          { required: true, message: "请上传营业执照", trigger: "change" },
        ],
        serviceCate: [
          { required: true, message: "请选择经营商品分类", trigger: "change" },
        ],
        serviceCode: [
          { required: true, message: "请选择经营商品类型", trigger: "change" },
        ],
        platformType: [
          { type: 'array', required: true, message: '请至少绑定一个主商户', trigger: 'change' }
        ],
        serviceTel: [
          { required: true, message: "请输入店铺电话", trigger: "blur" },
          // { validator: validateTel, trigger: 'change' }
        ],
      },
      rules1:{
        address: [
          { required: true, message: "请输入商铺地址或者点击地图", trigger: "blur" },
        ],
      }
    };
  },
  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)
    //              myGeo.getLocation(new BMapGL.Point(point.lng, point.lat), function(result){
    //                 if (result){
    //                   console.log(result);
    //                    // 选择营业地址时保存省市区
    //                   that.setQuery.province = result.addressComponents.province;
    //                   that.setQuery.city = result.addressComponents.city;
    //                   that.setQuery.district = result.addressComponents.district;
    //                 }
    //             });
    //            }
    //         }
    //     }, that.setQuery.city)
    //   }
    // }),
    "setQuery.shopMainId":function(val){
      if(val){
        this.finishComplexList()
      }else{
          this.authOptions = []

      }
    },
    'setQuery.authAccount'(val){
        if(!val){
          this.setQuery.state = 2
        }
    }
  },
  methods: {
    // 选择地址
    selectAddress(val){
      let item = this.addressOptions.filter(item=>item.value==val)[0]
      console.log(val,item);
      this.setQuery.mapLat = item.location.lat
      this.setQuery.mapLon = item.location.lng
      this.map.removeOverlay(this.marker); //移除点标记
      this.marker = new BMapGL.Marker(item.location, {title: val})
      this.map.addOverlay(this.marker)
      this.setQuery.province = item.province;
      this.setQuery.city = item.city;
      this.setQuery.district = item.district;
       this.map.centerAndZoom(item.location, 19);


    },
    // 查询地址
    searchAddress(val){
      if(val){
        this.addressLoading = true
        getSearchList({query:val,region:this.cityName,output:'json',ak:'7aGqlyBw6mGwS6vNMLbmMlsHqE2OGV0E'}).then(res=>{
          this.addressLoading = false
          if(res.status == 0){
            this.addressOptions = []
            res.result.map(item=>{
              this.addressOptions.push({
                label:item.name,
                value:item.address,
                location:item.location,
                province:item.province,
                city:item.city,
                district:item.district,
              })
            })
          }
        })
      }else{
            this.addressOptions = []

      }
      // ?query=天安门&region=北京&city_limit=true&output=json&ak=7aGqlyBw6mGwS6vNMLbmMlsHqE2OGV0E
      // }
    },
    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
          let obj = JSON.parse(JSON.stringify(this.setQuery))
          obj.serviceCode = obj.serviceCode.toString()
          let str = ''
          obj.serviceCate.map((item,index)=>{
            if(index != (obj.serviceCate.length -1 )){
              str += item.toString()+'/'
            }else{
              str += item.toString()
            }
          })
          obj.serviceCate = str
          obj.shopMenuId = obj.shopMenuId.toString()
          obj.platformType = obj.platformType.toString()
          if (this.setQuery.shopId) {
            this.update(obj);
          } else {
            this.add(obj);
          }
        }else{
          this.$message.error('请检查是否有必填项未填');
        }
      });
    },
    add(obj) {
      this.loading = true;

      add(obj).then((res) => {
        this.loading = false;
        if (res.state == "Success") {
          this.$notify({
            title: "成功",
            message: "操作成功",
            type: "success",
          });

          this.$router.push("/operationManage/shopManage/index");
        }
      });
    },
    update(obj) {
      this.loading = true;
      // let obj = JSON.parse(JSON.stringify(this.setQuery))
      // obj.serviceCode = obj.serviceCode.toString()
      // let str = ''
      // obj.serviceCate.map((item,index)=>{
      //   if(index != (obj.serviceCate.length -1 )){
      //     str += item.toString()+'/'
      //   }else{
      //      str += item.toString()
      //   }
      // })
      // obj.serviceCate = str
      // obj.shopMenuId = obj.shopMenuId.toString()
      // obj.platformType = obj.platformType.toString()

      update(obj).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;
          this.setQuery.serviceCode = this.setQuery.serviceCode.split(',')
          this.setQuery.serviceCate = this.setQuery.serviceCate.split('/').map(item=>{return item = item.split(',').map(item=> Number(item))})
          this.setQuery.shopMenuId = this.setQuery.shopMenuId.split(',').map(item=> Number(item))
          this.setQuery.platformType = this.setQuery.platformType.split(',')
        }
      });
    },
    // 获取经营类型
    getMenuName(){
      getMenuData().then(res=>{
        if(res.state == 'Success'){
             this.options = res.content
        }
      })
    },
    // 获取主体类型
    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",{enableIconClick: true});
        //  var point = new BMapGL.Point(this.setQuery.mapLon,this.setQuery.mapLat);
        // this.map.centerAndZoom(point, 15);
        var geoc = new BMapGL.Geocoder();
        this.map.enableScrollWheelZoom(true)
        var myCity = new BMapGL.LocalCity();
        myCity.get((result)=> {
          console.log(result);
          that.cityName =  result.name
          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) {
          let itemId = that.map.getIconByClickPosition(e)
          console.log(1111111,itemId);

          if (itemId) {
            uidToAddress({uid:itemId.uid,scope:2,output:'json',ak:'7aGqlyBw6mGwS6vNMLbmMlsHqE2OGV0E'}).then(res=>{
              if(res.status == 0){
                console.log(res.result);
                 that.setQuery.mapLat = res.result.location.lat
                that.setQuery.mapLon = res.result.location.lng
                that.map.removeOverlay(that.marker); //移除点标记
                that.marker = new BMapGL.Marker(res.result.location, {title: res.result.name})
                that.map.addOverlay(that.marker)
                that.setQuery.address = res.result.name+'-'+ res.result.address;
                that.setQuery.province = res.result.province;
                that.setQuery.city = res.result.city;
                that.setQuery.district = res.result.area;
                that.map.centerAndZoom(res.result.location, 19);
              }
            })
            // let url = "//api.map.baidu.com/?qt=inf&uid="+itemId.uid+'&operate=mapclick&clicktype=tile&ie=utf-8&oue=1&fromproduct=jsapi&res=api&&ak=7aGqlyBw6mGwS6vNMLbmMlsHqE2OGV0E&callback=sucess'

          }
          // 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.$refs.address.validate((v) => {
        if (v) {
          this.$confirm('请确认地址信息准确无误，并精确到门牌号?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.showMap = false
          })
        }
      })
    },
    // 规则
    getRuleList() {
      getRuleList({currentPage:1,pageSize:999}).then((res) => {
        if (res.state == "Success") {
          res.content.records.map(item=>{
            this.ruleOptions.push({
              label:item.shareRule,
              value:item.id
            })
          })
        }
      });
    },
    // 获取商品分类
    getData(){
      getData().then(res=>{
        if(res.state == 'Success'){
          // this.typeOptions = res.content
           this.typeOptions = res.content.map(e=>{
            try{
              e.child.map(
              r=>{
                delete r.child
                return r
              }
            )
            }catch(e){
              console.log(e);
            }
            return e
          });
        }
      })
    },
    // 获取当前主体下面的已签约银联账号
    finishComplexList(){
      finishComplexList({
        "accesseId": "",
        "epId": this.setQuery.shopMainId
      }).then(res=>{
         if(res.state == 'Success'){
          let list = []
          res.content.map(item=>{
              list.push({
                value:item.accesser_user_id,
                label:item.externalName
              })
          })
          this.authOptions = list
        }
      })
    }
  },
  created() {
    // this.finishComplexList()
    this.getData()
    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;
  }
  .address-input-box {
  display: flex;
  .address-input {
    flex: 1;
  }
}
}
</style>
