<template>
  <div class="AppMerchantList">
    <ai-list>
      <template slot="title">
        <ai-title title="商户管理" :isShowBottomBorder="false" :isShowArea="false"></ai-title>
      </template>
      <template slot="content">
        <ai-search-bar>
          <template #left>
            <ai-select
              v-model="search.status"
              placeholder="选择审核类型"
              clearable
              @change="(page.current = 1), getList()"
              :selectList="dict.getDict('tfx_merchantStatus')"
            ></ai-select>
          </template>
          <template #right>
            <el-input v-model="search.merchantName" class="search-input" size="small" placeholder="请输入商户名称" clearable @change="getList" @clear="page.current = 1, (search.merchantName = ''), getList()" suffix-icon="iconfont iconSearch">
            </el-input>
          </template>
        </ai-search-bar>
        <ai-table :tableData="tableData" :colConfigs="colConfigs" :total="page.total" :current.sync="page.current"
          :size.sync="page.size" @getList="getList" class="ai-table">
          <el-table-column slot="logoFiles" label="门店照片" align="left">
            <template slot-scope="{ row }" v-if="row.logoFiles.length">
              <el-image class="row-img" :src="row.logoFiles[0].accessUrl" :preview-src-list="row.logoFilesUrlList"/>
            </template>
          </el-table-column>
          <el-table-column slot="userName" label="微信用户" align="left">
            <template slot-scope="{ row }">
              <el-image class="user-img" :src="row.userAvatarUrl" :preview-src-list="[row.userAvatarUrl]"/>
              <span class="user-name">{{row.userName}}</span>
            </template>
          </el-table-column>
          <el-table-column slot="option" label="操作" align="center" width="250">
            <template slot-scope="{row}">
              <el-button type="text" v-if="row.status == 0" @click="examine(row, 1, '确定通过该商户审核？')">审核通过</el-button>
              <el-button type="text" v-if="row.status == 0" @click="examine(row, 0, '确定拒绝该商户审核？')">审核拒绝</el-button>
              <el-button type="text" v-if="row.status == 1" @click="add(row)">编辑</el-button>
            </template>
          </el-table-column>
        </ai-table>
      </template>
    </ai-list>
    <ai-dialog title="商户修改" :visible.sync="visible" @onCancel="visible = false; dialogInfo = {}" @onConfirm="addConfirm" width="800px">
      <el-form ref="ruleForm" :model="dialogInfo" :rules="formRules" size="small" label-width="120px">
        <el-form-item label="门店照片" prop="logoFiles">
          <ai-uploader v-model="dialogInfo.logoFiles" :instance="instance" :limit="9"></ai-uploader>
        </el-form-item>
        <el-form-item label="商户名称" prop="merchantName">
          <el-input placeholder="请输入商户名称" :maxlength="30" show-word-limit v-model="dialogInfo.merchantName"></el-input>
        </el-form-item>
        <el-form-item style="width: 100%" label="地理位置" prop="address">
          <el-button @click="showMap = true">地图标绘</el-button>
        </el-form-item>
        <el-form-item label="标绘地址">
          <el-input v-model="dialogInfo.address" disabled ></el-input>
        </el-form-item>
      </el-form>
    </ai-dialog>
    <ai-dialog title="地图" :visible.sync="showMap" @opened="initMap" width="800px" class="mapDialog" @onConfirm="selectMap">
      <div id="map"></div>
      <el-form label-width="80px" style="padding: 10px 20px 0 20px;">
        <el-row type="flex" justify="space-between">
          <el-form-item label="经度">
            <el-input disabled size="small" v-model="placeDetail.lng"></el-input>
          </el-form-item>
          <el-form-item label="纬度">
            <el-input disabled size="small" v-model="placeDetail.lat"></el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <el-input id="searchPlaceInput" size="medium" class="searchPlaceInput" clearable v-model="searchPlace" autocomplete="on" @change="placeSearch.search(searchPlace)" placeholder="请输入关键字">
        <el-button type="primary" slot="append" @click="placeSearch.search(searchPlace)">搜索</el-button>
      </el-input>
      <div id="searchPlaceOutput" />
    </ai-dialog>
  </div>
</template>

<script>
import {mapState} from 'vuex'
import AMapLoader from '@amap/amap-jsapi-loader'
export default {
  label: '商户管理',
  name: 'AppMerchantList',
  props: {
    instance: Function,
    dict: Object,
    permissions: Function,
  },
  data() {
    return {
      tableData: [],
      page: {
        size: 10,
        current: 1,
        total: 0,
      },
      search: {
        merchantName: '',
        status: ''
      },
      visible: false,
      dialogInfo: {},
      showMap: false,
      map: null,
      placeSearch: null,
      placeDetail: {
        lng: '',
        lat: '',
        address: ''
      },
      searchPlace: '',
      formRules: {
        logoFiles: [{required: true, message: '请上传商户图片', trigger: 'blur'}],
        merchantName: [{required: true, message: '请输入商户名称', trigger: 'blur'}],
        address: [{required: true, message: '请输入选择地理位置', trigger: 'blur'}],
      },
      colConfigs: [
        {slot: 'logoFiles'},
        {prop: 'merchantName', label: '商户名称', width: 120, align: 'center'},
        {prop: 'address', label: '地理位置', align: 'center'},
        {slot: 'userName'},
        {prop: 'status', label: '状态', align: 'center', dict: 'tfx_merchantStatus'},
        {slot: 'option'},
      ],
    }
  },
  computed: {
    ...mapState(['user']),
  },
  created() {
    this.$dict.load('tfx_merchantStatus').then(()=> {
      this.getList()
    })
  },
  mounted() {
  },
  methods: {
    add(row) {
      this.dialogInfo = {...row}
      // this.dialogInfo.photoList = [{url: row.photoUrl}]
      this.visible = true
    },
    selectMap() {
      this.dialogInfo.lng = this.placeDetail.lng
      this.dialogInfo.lat = this.placeDetail.lat
      this.dialogInfo.address = this.placeDetail.address
      this.showMap = false
    },
    initMap() {
      AMapLoader.load({
        key: '54a02a43d9828a8f9cd4f26fe281e74e',
        version: '2.0',
        plugins: ['AMap.PlaceSearch', 'AMap.AutoComplete', 'AMap.Geocoder'],
      }).then((AMap) => {
        this.map = new AMap.Map('map', {
          resizeEnable: true,
          zooms: [6, 20],
          zoom: 11,
          center:[104.067923463, 30.6799428454],
        })
        this.placeSearch = new AMap.PlaceSearch({ map: this.map })
        new AMap.AutoComplete({
          input: 'searchPlaceInput',
          output: 'searchPlaceOutput',
        }).on('select', (e) => {
          if (e?.poi) {
            this.placeSearch.setCity(e.poi.adcode)
            this.movePosition(e.poi.location)
          }
        })
        this.map.on('click', (e) => {
          new AMap.Geocoder().getAddress(e.lnglat, (sta, res) => {
            if (res?.regeocode) {
              this.placeDetail = {
                lng: e.lnglat?.lng,
                lat: e.lnglat?.lat,
                address: res.regeocode.formattedAddress,
              }
            }
          })
          this.movePosition(e.lnglat)
        })
      })
    },
    movePosition(center) {
      if (this.map) {
        this.map.clearMap()
        this.map.panTo(center)
        this.map.add([
          new AMap.Marker({
            position: center,
            clickable: true,
          }),
        ])
        this.map.setFitView()
      }
    },
    addConfirm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // this.dialogInfo.photoUrl = this.dialogInfo.photoList[0].url
          this.instance.post(`api/appmerchantinfo/addOrUpdate`, {...this.dialogInfo}).then(res => {
            if (res?.code == 0) {
              this.$message.success('商户修改成功')
              this.visible = false
              this.getList()
            }
          })
        }
      })
    },
    examine(row, pass, text) {
      this.$confirm(text).then(() => {
        this.instance.post(`api/appmerchantinfo/examine?id=${row.id}&pass=${pass}`).then(res => {
          if (res.code == 0) {
            this.$message.success('审核成功')
            this.getList()
          }
        })
      })
    },
    getList() {
      this.instance.post(`api/appmerchantinfo/list`, null, {
        params: {
          ...this.page,
          ...this.search
        },
      }).then((res) => {
        if (res.code == 0) {
          res.data.records.map((item) => {
            item.logoFilesUrlList = []
            if(item.logoFiles) {
              item.logoFiles.map((e) => {
                item.logoFilesUrlList.push(e.accessUrl)
              })
            }
          })
          this.tableData = res.data.records
          this.page.total = res.data.total
        }
      })
      .catch(() => {
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.AppMerchantList {
  height: 100%;
  ::v-deep .endIntegral .el-form-item__content {
    margin-left: 0!important;
  }
  .row-img {
    width: 80px;
    height: 80px;
  }
  .user-img {
    width: 40px;
    height: 40px;
    border-radius: 50%;
  }
  .user-name {
    display: inline-block;
    line-height: 40px;
    vertical-align: text-bottom;
    margin-left: 8px;
  }
}
</style>
