<template>
  <div class="app-container">
    <el-tabs v-model="active">
      <el-tab-pane label="门店列表" name="table">
        <!-- 查询和其他操作 -->
        <div class="filter-container">
          <el-input v-model="listQuery.name" clearable class="filter-item" style="width: 200px;" placeholder="请输入门店" />
          <el-select v-model="listQuery.shopCity" clearable style="width: 200px" class="filter-item"
            placeholder="请选择所属城市" filterable>
            <el-option v-for="type in citys" :key="type.id" :label="type.cityName" :value="type.id" />
          </el-select>
          <el-select v-model="listQuery.channelId" clearable style="width: 150px" class="filter-item"
            placeholder="请选择渠道">
            <el-option v-for="type in channels" :key="type.id" :label="type.name" :value="type.id" />
          </el-select>

          <el-select v-model="listQuery.shopType" clearable style="width: 200px" class="filter-item"
            placeholder="请选择门店类型" filterable>
            <el-option label="POI门店" :value="0" />
            <el-option label="虚拟门店" :value="1" />
          </el-select>

          <el-select v-model="listQuery.isBinding" clearable style="width: 260px" class="filter-item"
            placeholder="请选择是否绑定全部商品" filterable>
            <el-option label="未绑定" :value="0" />
            <el-option label="已绑定" :value="1" />
          </el-select>

          <el-button v-permission="['GET /admin/shop/list']" class="filter-item" type="primary" icon="el-icon-search"
            @click="handleFilter">查找</el-button>
          <el-button v-permission="['POST /admin/shop/create']" class="filter-item" type="primary" icon="el-icon-edit"
            @click="handleCreate">添加</el-button>
          <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download"
            @click="handleDownload">导出</el-button>
          <el-button :loading="syncMtShopLoading" class="filter-item" type="primary" icon="el-icon-download"
            @click="syncMtShop">同步美团门店</el-button>
        </div>
        <!-- 查询结果 -->
        <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>
          <el-table-column align="center" label="门店编号" prop="shopNo" sortable width="160" />
          <el-table-column align="center" label="门店信息" prop="shopNo" sortable width="360">
            <template slot-scope="scope">
              <div style="text-align: left;">
                <span style="font-weight: 600;">门店POI:</span> {{ scope.row.poiId }}<br />
                <span style="font-weight: 600;">门店名称:</span><span> {{ scope.row.shopName }}</span><br />
                <span style="font-weight: 600;">门店渠道:</span><span> <el-tag type="primary">{{ scope.row.shopChannel |
      channelsFilter }}</el-tag></span><br />
                <div style="margin: 3px 0;"><span style="font-weight: 600;">门店类型:</span><span> <el-tag
                      :type="scope.row.shopType == 0 ? 'success' : 'danger'">{{
      scope.row.shopType == 0 ? 'POI门店' : '虚拟门店' }}</el-tag>
                    <el-tag :type="scope.row.isVerify ? 'success' : 'primary'">{{ scope.row.isVerify ? '核销门店' : '非核销门店'
                      }}</el-tag></span></div>
              </div>
            </template>
          </el-table-column>
          <!-- <el-table-column align="center" label="门店名称" prop="shopName" />
          <el-table-column align="center" label="门店渠道" prop="shopChannel" width="100">
            <template slot-scope="scope">
              <el-tag type="primary">{{ scope.row.shopChannel | channelsFilter }}</el-tag>
            </template>
          </el-table-column> -->
          <el-table-column align="center" label="加盟商" prop="shopCityName">
            <template slot-scope="scope">
              <div style="text-align: left;">
                <span style="font-weight: 600;">门店城市:</span> {{ scope.row.shopCityName }}<br />
                <span style="font-weight: 600;">加盟商ID:</span><span> {{ scope.row.fraId }}</span><br />
                <span style="font-weight: 600;">加盟商名称:</span><span>{{ scope.row.fraName }}</span><br />
              </div>
            </template>
          </el-table-column>

          <el-table-column align="center" label="状态" prop="shopCityName" width="250">
            <template slot-scope="scope">
              <div style="text-align: left;">
                <span style="font-weight: 600;">可用状态:</span> <el-tag v-if="scope.row.deleted == true"
                  type="danger">已停用</el-tag>
                <el-tag v-else>正常</el-tag><br />
                <span style="font-weight: 600;">抖音同步状态:</span><span> <el-tag
                    v-if="scope.row.shopChannel === 26 && scope.row.poiId && scope.row.supplierId">已同步</el-tag>
                  <el-tag v-else type="danger">未同步</el-tag></span><br />
                <span style="font-weight: 600;">录入时间:</span><span>{{ scope.row.createTime }}</span><br />
                <span style="font-weight: 600;">修改时间:</span><span>{{ scope.row.updateTime }}</span><br />
              </div>
            </template>
          </el-table-column>

          <el-table-column align="center" label="绑定状态" prop="shopCityName" width="300">
            <template slot-scope="scope">
              <div style="text-align: left;">
                <span style="font-weight: 600;">抖音绑定商品:</span><span> <el-tag
                    v-if="scope.row.shopChannel === 26 && scope.row.isBinding">绑定全部</el-tag>
                  <el-tag v-else type="danger">未绑全</el-tag></span><br />
                <span style="font-weight: 600;">绑定日志:</span><span>{{ scope.row.bindingLog }}</span><br />
              </div>
            </template>
          </el-table-column>


          <el-table-column align="center" label="操作" class-name="small-padding fixed-width">

            <template slot-scope="scope">
              <!--              <el-button v-permission="['GET /admin/dyshop/syncShop']" type="success" size="mini" style="width: 90px"-->
              <!--                @click="handleSync(scope.row)"-->
              <!--                v-if="scope.row.shopChannel === 26 && !scope.row.supplierId">创建抖音门店</el-button>-->
              <el-button v-permission="['POST /admin/shop/update']" type="primary" size="mini"
                @click="handleUpdate(scope.row)">编辑</el-button>
              <el-button v-permission="['POST /admin/shop/delete']" type="danger" size="mini"
                @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
          @pagination="getList" />
      </el-tab-pane>
      <el-tab-pane label="抖音门店地图" name="map">
        <div class="filter-container">
          <el-input v-model="address" clearable class="filter-item" style="width: 400px;" placeholder="请输入加盟地址" />
          <el-button class="filter-item" type="primary" icon="el-icon-search" @click="getAllShopPosition">查找</el-button>
        </div>
        <div id="container" style=" height: 900px; width: 100%;"></div>
      </el-tab-pane>
    </el-tabs>


    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="700px">
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="100px"
        style="width: 500px; margin-left:50px;">

        <el-form-item label="所属城市" prop="shopCity">
          <el-select v-model="dataForm.shopCity" clearable style="width: 200px" class="filter-item"
            placeholder="请选择所属城市" filterable>
            <el-option v-for="type in citys" :key="type.id" :label="type.cityName" :value="type.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="所属渠道" prop="shopChannel">
          <el-select v-model="dataForm.shopChannel" @change="getServiceStore" clearable style="width: 200px"
            class="filter-item" placeholder="请选择渠道">
            <el-option v-for="type in channels" :key="type.id" :label="type.name" :value="type.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="门店类型" prop="shopType">
          <el-select v-model="dataForm.shopType" clearable class="filter-item" placeholder="请选择门店类型" filterable>
            <el-option label="POI门店" :value="0" />
            <el-option label="虚拟门店" :value="1" />
          </el-select>
        </el-form-item>

        <el-form-item label="加盟商ID " prop="fraId">
          <el-input v-model="dataForm.fraId" placeholder="鲸致公司请填入293" />
        </el-form-item>

        <el-form-item label="门店名称" prop="shopName">
          <el-input v-model="dataForm.shopName" placeholder="请填写门店名称" />
        </el-form-item>

        <el-form-item label="门店地址" prop="shopAddress">
          <el-input v-model="dataForm.shopAddress" placeholder="请填写门店名详细地址" />
        </el-form-item>
        <el-form-item label="门店经纬度" prop="shopPosition">
          <el-input v-model="dataForm.shopPosition" placeholder="逗号分割 如：121.526761,31.142489" />
        </el-form-item>

        <el-form-item label="抖音poi-id" prop="poiId">
          <el-input v-model="dataForm.poiId" placeholder="抖音门店的poi id" />
        </el-form-item>


        <el-form-item label="核销类型" prop="isVerify">
          <el-select v-model="dataForm.isVerify" clearable style="width: 200px" class="filter-item"
            placeholder="请选择核销类型">
            <el-option v-for="type in verifyOptions" :key="type.value" :label="type.label" :value="type.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="deleted">
          <el-select v-model="dataForm.deleted" clearable style="width: 200px" class="filter-item" placeholder="请选择状态">
            <el-option v-for="type in deletedOptions" :key="type.value" :label="type.label" :value="type.value"
              :disabled="type.disabled = true" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus == 'create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { createShop, deleteShop, getStoreBySourceNo, listShop, updateShop, syncShop, selectAllPosition, syncMeiTuanShop } from '@/api/shop'
import { listAllCity } from '@/api/city'
import { allChannel } from '@/api/channel'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
let vm

export default {
  name: 'Shop',
  components: { Pagination },
  filters: {
    channelsFilter(value) {
      const rs = vm.channels.filter((item) => {
        return item.id === value
      })

      if (rs != null && rs.length > 0) { return rs[0].name }
    }
  },
  data() {
    var PoiIdValid = (rule, value, callback) => {
      if (this.dataForm.shopChannel == 26 && this.dataForm.shopType == 0 && (value == null || value == "")) {
        callback(new Error("请填写抖音门店POIID"));
      } else {
        callback();
      }
    };
    return {
      map: "",
      cluster: '',
      markers: [],
      active: "map",
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        name: undefined,
        shopCity: undefined,
        page: 1,
        limit: 20,
        sort: 'create_time',
        order: 'desc',
        channelId: null
      },
      channels: [],
      serviceStoreList: [],
      dataForm: {
        id: undefined,
        shopId: '',
        shopName: '',
        shopAddress: '',
        shopPosition: '',
        deleted: false,
        shopCity: undefined,
        shopChannel: undefined,
        poiId: '',
        serviceStoreId: '',//临时字段
        fraId: ''
      },
      citys: [],
      deletedOptions: [{
        value: false,
        label: '正常',
        disabled: true
      }, {
        value: true,
        label: '删除',
        disabled: true
      }],

      verifyOptions: [{
        value: false,
        label: '非核销门店'
      }, {
        value: true,
        label: '核销门店'
      }],
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        shopName: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        shopCity: [{ required: true, message: '城市不能为空', trigger: 'blur' }],
        shopChannel: [{ required: true, message: '渠道不能为空', trigger: 'blur' }],
        shopAddress: [{ required: true, message: '门店地址不能为空', trigger: 'blur' }],
        shopPosition: [{ required: true, message: '门店经纬度不能为空', trigger: 'blur' }],
        // poiId: [{ required: true, message: '抖音poi-id不能为空', trigger: 'blur' }],
        // shopNo: [{ required: true, message: '编号不能为空', trigger: 'blur' }],
        fraId: [{ required: true, message: '加盟商id不能为空', trigger: 'blur' }],
        deleted: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
        shopType: [{ required: true, message: '门店类型不能为空', trigger: 'blur' }],
        poiId: [{ validator: PoiIdValid, required: true, message: '门店类型不能为空', trigger: 'blur' }],
      },
      downloadLoading: false,
      address: '',//加盟地址
      syncMtShopLoading: false
    }
  },
  beforeCreate() {
    vm = this
  },
  created() {
    this.getList()
    allChannel().then(res => {
      this.channels = [];
      res.data.data.forEach(ch => {
        if (ch.id == 26 || ch.id == 103 || ch.id == 104||ch.id==110)
          this.channels.push(ch)
      })
    })
    listAllCity().then(res => {
      this.citys = res.data.data
    })
  },
  mounted() {
    this.getAllShopPosition();
  },
  methods: {
    // chooseStore(e) {
    //   this.dataForm.shopNo = e;
    //   this.dataForm.shopName = this.serviceStoreList.find(item => item.id === e).unitName;
    //   this.dataForm.shopAddress = this.serviceStoreList.find(item => item.id === e).address;
    // },
    getServiceStore() {
      // alert(this.dataForm.shopChannel);
      getStoreBySourceNo({ channelId: this.dataForm.shopChannel }).then(res => {
        this.serviceStoreList = res.data.data;
      })
    },
    getList() {
      this.listLoading = true
      listShop(this.listQuery).then(response => {
        this.list = response.data.data.list
        this.total = response.data.data.total
        this.listLoading = false
      }).catch(() => {
        this.list = []
        this.total = 0
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        shopId: '',
        shopName: '',
        deleted: false,
        serviceStoreId: '',
        shopAddress: '',
        shopPosition: '',
        poiId: '',
        fraId: '',
        isVerify: false
      }
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {

          if (this.dataForm.shopType != 0 && this.dataForm.isVerify) {
            this.$notify.warning({
              title: '提醒',
              message: '非POI门店不允许设置为核销门店'
            })
            return;
          }

          createShop(this.dataForm).then(response => {
            this.list.unshift(response.data.data)
            this.dialogFormVisible = false
            this.$notify.success({
              title: '成功',
              message: '创建成功'
            })
          }).catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
        }
      })
    },
    getAllShopPosition() {
      selectAllPosition({ channelId: 26, 'address': this.address }).then(res => {
        this.initMap(res.data.data);
        //存在逆地址解析
        if (this.address != '' && res.data.data.myPosition.point == null) {
          this.$notify.error({
            title: '失败',
            message: '填写地址无法解析，请输入完整'
          })
        }
      })
    },
    initMap(data) {
      var markers = [];
      let map = new AMap.Map("container", {
        center: [105, 34],
        zoom: 5,
        resizeEnable: true,
      });

      let points = data.points;
      let gray = "https://mall.zhaijieshi.cc/file/jzmall/storage/11tzxtjpbuxl4va6j2qt.png";
      let red = "https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png";
      let blue = "https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png";
      let yellow = "https://mall.zhaijieshi.cc/file/jzmall/storage/htsvfj1bc8sqhhwgnlcj.png";//临时黄色

      for (var i = 0; i < points.length; i += 1) {
        let icon = blue;
        if (points[i]['name'].indexOf('临时') >= 0)
          icon = yellow;
        else if (points[i]['fraId'] && points[i]['fraId'] == 10418)
          icon = gray;
        else if (points[i]['fraId'] && points[i]['fraId'] != 10418 && points[i]['fraId'] != 293)
          icon = red;

        var marker = new AMap.Marker({
          icon: icon,
          position: points[i]['point'],
          //content: '<div style="background-color: hsla(180, 100%, 50%, 0.7); height: 24px; width: 24px; border: 1px solid hsl(180, 100%, 40%); border-radius: 12px; box-shadow: hsl(180, 100%, 50%) 0px 0px 1px;"></div>',
          offset: new AMap.Pixel(-15, -15)
        });
        marker.setTitle(points[i]['name']);
        markers.push(marker);
      }
      //是否存在逆地址
      if (data.myPosition.point != null) {
        var marker = new AMap.Marker({
          icon: "https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png",
          position: data.myPosition.point,
          offset: new AMap.Pixel(-15, -15)
        });
        marker.setTitle(data.myPosition.name);
        markers.push(marker);
        marker.setLabel({
          offset: new AMap.Pixel(0, -10),  //设置文本标注偏移量
          content: "<div class='info'>我在这里</div>", //设置文本标注内容
          direction: 'right' //设置文本标注方位
        });
        map.setCenter(data.myPosition.point);
        map.setZoom(13);
      }

      if (this.cluster) {
        this.cluster.setMap(null);
      }
      //console.info(markers)
      this.cluster = new AMap.MarkerClusterer(map, markers, { gridSize: 10 });
    },
    handleSync(row) {
      console.log(row);
      if (row.delete) {
        this.$notify.error("该门店已经删除，不能同步");
      }
      const test = row.poiId && row.shopAddress && row.shopNo && row.shopNo;
      if (!test) {
        this.$notify.error("待同步门店poiId、shopAddress、shopNo不能为空，请先编辑信息");
      }
      const synced = row.shopChannel === 26 && row.supplierId;
      if (synced) {
        this.$notify.error("该门店已经同步，不能重复同步");
      }


      const param = {
        shopIds: [row.id]
      }
      const loading = this.$loading({
        lock: true,
        text: "努力同步中，请稍侯...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.5)",
      });
      syncShop(param).then((res) => {
        if (res.data.error === 0) {
          this.$notify.success({
            title: '成功',
            message: '同步成功'
          })
          loading.close();
          this.getList();
        } else {
          this.$notify.error({
            title: '失败',
            message: res.data.data[0].msg
          })
          loading.close();
        }
      }).catch((err) => {
        this.$notify.error({
          title: '失败',
          message: err
        })
        loading.close();
      })

    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dataForm.serviceStoreId = row.shopNo;
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      // this.getServiceStore();
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.dataForm.shopType != 0 && this.dataForm.isVerify) {
            this.$notify.warning({
              title: '提醒',
              message: '非POI门店不允许设置为核销门店'
            })
            return;
          }
          
          updateShop(this.dataForm).then(() => {
            for (const v of this.list) {
              if (v.id === this.dataForm.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.dataForm)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify.success({
              title: '成功',
              message: '更新成功'
            })
          }).catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
        }
      })
    },
    handleDelete(row) {
      deleteShop(row).then(response => {
        this.$notify.success({
          title: '成功',
          message: '删除成功'
        })
        const index = this.list.indexOf(row)
        this.list.splice(index, 1)
      }).catch(response => {
        this.$notify.error({
          title: '失败',
          message: response.data.errmsg
        })
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['门店编号', '门店名称', '加盟商', '门店渠道', '城市', '状态']
        const filterVal = ['shopNo', 'shopName', 'fraName', 'shopChannel', 'shopCityName', 'deleted']
        excel.export_json_to_excel2(tHeader, this.list, filterVal, '门店列表')
        this.downloadLoading = false
      })
    },
    syncMtShop() {
      this.syncMtShopLoading = true
      syncMeiTuanShop().then(res => {
        this.$notify.success({
          title: '成功',
          message: res.data.errmsg
        })
      }).catch(response => {
        this.$notify.error({
          title: '失败',
          message: response.data.errmsg
        })
      })
      this.syncMtShopLoading = false
    }
  }
}
</script>

<style>
.marker {
  position: absolute;
  top: -20px;
  right: -118px;
  color: #fff;
  padding: 4px 10px;
  box-shadow: 1px 1px 1px rgba(10, 10, 10, .2);
  white-space: nowrap;
  font-size: 12px;
  font-family: "";
  background-color: #25A5F7;
  border-radius: 3px;
}

.amap-icon img,
.amap-marker-content img {
  width: 25px;
  height: 34px;
}

.marker {
  position: absolute;
  top: -20px;
  right: -118px;
  color: #fff;
  padding: 4px 10px;
  box-shadow: 1px 1px 1px rgba(10, 10, 10, .2);
  white-space: nowrap;
  font-size: 12px;
  font-family: "";
  background-color: #25A5F7;
  border-radius: 3px;
}
</style>
