<template>
  <section class="AppQyWxConfig">
    <ai-list>
      <ai-title slot="title" title="企业微信配置" isShowBottomBorder/>
      <template #content>
        <ai-search-bar>
          <template #left>
            <el-button type="primary" @click="add" icon="iconfont iconAdd">新增</el-button>
          </template>
          <template #right>
            <el-input size="small" placeholder="搜索名称" v-model="search.name" clearable
                      @change="page.current=1,getTableData()"/>
          </template>
        </ai-search-bar>
        <ai-table :tableData="tableData" :total="page.total" :current.sync="page.current" :size.sync="page.size"
                  @getList="getTableData" :col-configs="colConfigs">
          <el-table-column slot="status" align="center" label="状态" width="150">
            <template v-slot="{ row }">
              <el-switch v-model="row.status" @change="onChange(row)" active-value="1" inactive-value="0"
                         active-color="#5088FF" inactive-color="#D0D4DC"></el-switch>
            </template>
          </el-table-column>
          <el-table-column slot="options" align="center" label="操作" fixed="right" width="200px">
            <el-row type="flex" justify="center" align="middle" slot-scope="{row}">
              <el-button type="text" @click="detail(row)">详情</el-button>
              <el-button type="text" @click="del(row)">删除</el-button>
              <el-button type="text" @click="handleSystemInfo(row.id)">系统信息</el-button>
            </el-row>
          </el-table-column>
        </ai-table>
      </template>
    </ai-list>

    <ai-dialog title="新增" :visible.sync="dialog" width="800px" @onConfirm="confirm">
      <el-form ref="form" :model="dialogForm" :rules="rules" size="small" label-width="180px">
        <el-form-item required label="名称" prop="name">
          <el-input v-model.trim="dialogForm.name" placeholder="请输入名称" show-word-limit maxlength="100"></el-input>
        </el-form-item>
        <el-form-item label="企业微信ID" prop="corpId">
          <el-input v-model.trim="dialogForm.corpId" placeholder="请输入企业微信ID" show-word-limit maxlength="32"></el-input>
        </el-form-item>
        <el-form-item label="企业微信通讯录SECRET" prop="corpAddressBookSecret">
          <el-input v-model.trim="dialogForm.corpAddressBookSecret" placeholder="请输入企业微信通讯录SECRET" show-word-limit
                    maxlength="64"></el-input>
        </el-form-item>
        <el-form-item label="企业微信AESKEY" prop="corpAeskey">
          <el-input v-model.trim="dialogForm.corpAeskey" placeholder="请输入企业微信AESKEY" show-word-limit
                    maxlength="64"></el-input>
        </el-form-item>
        <el-form-item label="企业微信AGENTID" prop="corpAgentId">
          <el-input v-model.trim="dialogForm.corpAgentId" placeholder="请输入企业微信AGENTID" show-word-limit
                    maxlength="100"></el-input>
        </el-form-item>
        <el-form-item label="企业微信SECRET" prop="corpSecret">
          <el-input v-model.trim="dialogForm.corpSecret" placeholder="请输入企业微信SECRET" show-word-limit
                    maxlength="255"></el-input>
        </el-form-item>
        <el-form-item label="企业微信TOKEN" prop="corpToken">
          <el-input v-model.trim="dialogForm.corpToken" placeholder="请输入企业微信TOKEN" show-word-limit
                    maxlength="32"></el-input>
        </el-form-item>
        <el-form-item label="小程序APPID" prop="miniappAppid">
          <el-input v-model.trim="dialogForm.miniappAppid" placeholder="请输入小程序APPID" show-word-limit
                    maxlength="32"></el-input>
        </el-form-item>
        <el-form-item label="小程序SECRET" prop="miniappSecret">
          <el-input v-model.trim="dialogForm.miniappSecret" placeholder="请输入小程序SECRET" show-word-limit
                    maxlength="32"></el-input>
        </el-form-item>
        <el-form-item label="访问域名" prop="dvcpUrl">
          <el-input v-model.trim="dialogForm.dvcpUrl" placeholder="请输入访问域名" show-word-limit maxlength="128">
            <template slot="prepend">Http://</template>
          </el-input>
        </el-form-item>
        <el-form-item label="地区" prop="areaId">
          <ai-area-select :instance="instance" v-model="dialogForm.areaId" alwaysShow
                          @name="(e)=>dialogForm.areaName=e"/>
        </el-form-item>
        <el-form-item label="地图中心点" prop="lat">
          <el-button type="primary" icon="iconfont iconAdd" @click="showMap=true">设置地点</el-button>
          <div v-if="dialogForm.lat">{{ dialogForm.address }}</div>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model.trim="dialogForm.status">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">禁用</el-radio>
          </el-radio-group>
        </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-input id="searchPlaceInput" size="medium" class="searchPlaceInput" clearable v-model="searchPlace"
                autocomplete="on"
                @change="placeSearch.search(searchPlace)">
        <el-button type="primary" slot="append" @click="placeSearch.search(searchPlace)">搜索</el-button>
      </el-input>
      <div id="searchPlaceOutput"/>
    </ai-dialog>
    <ai-dialog title="系统信息设置" :visible.sync="sysInfoDialog" width="600px" @onConfirm="submitSystemInfo" @closed="sysInfo={}">
      <el-form size="small" label-width="140px">
        <el-form-item label="页签标题">
          <el-input v-model="sysInfo.title" placeholder="请输入..." clearable/>
        </el-form-item>
        <el-form-item label="系统标题">
          <el-input v-model="sysInfo.fullTitle" placeholder="请输入..." clearable/>
        </el-form-item>
        <el-form-item label="logo">
          <el-input v-model="sysInfo.logo" placeholder="请输入..." clearable/>
        </el-form-item>
        <el-form-item label="登录页左上角标题">
          <el-input v-model="sysInfo.name" placeholder="请输入..." clearable/>
        </el-form-item>
        <el-form-item label="登录页副标题">
          <el-input type="textarea" rows="5" v-model="sysInfo.desc" placeholder="请输入..." clearable/>
        </el-form-item>

        <el-form-item label="版权所有">
          <el-input v-model="sysInfo.recordDesc" placeholder="请输入..." clearable/>
        </el-form-item>
        <el-form-item label="备案号">
          <el-input v-model="sysInfo.recordNo" placeholder="请输入..." clearable/>
        </el-form-item>
        <el-form-item label="备案跳转链接">
          <el-input v-model="sysInfo.recordURL" placeholder="请输入..." clearable/>
        </el-form-item>
      </el-form>
    </ai-dialog>
  </section>
</template>

<script>
import {mapState} from "vuex";
import AMapLoader from "@amap/amap-jsapi-loader"

export default {
  name: "AppQyWxConfig",
  label: "企业微信配置",
  props: {
    instance: Function,
    dict: Object,
    permissions: Function
  },
  computed: {
    ...mapState(['user']),
    colConfigs() {
      return [
        {prop: "name", label: "名称", width: 150},
        {prop: "corpId", label: "企业微信ID", width: 180},
        {prop: "corpAddressBookSecret", label: "企业微信通讯录SECRET", width: 200},
        {prop: "corpAgentId", label: "企业微信AGENTID", width: 150},
        {prop: "corpSecret", label: "企业微信SECRET", width: 200},
        {prop: "corpToken", label: "企业微信TOKEN", width: 150},
        {prop: "corpAeskey", label: "企业微信AESKEY", width: 150},
        {prop: "miniappAppid", label: "小程序APPID", width: 150},
        {prop: "miniappSecret", label: "小程序SECRET", width: 150},
        {prop: "lat", label: "纬度", width: 100},
        {prop: "lng", label: "经度", width: 100},
        {prop: "address", label: "中心点", width: 100},
        {slot: "status",},
        {prop: "createTime", label: "创建时间", width: 150},
        {slot: "options"},
      ]
    },
    rules() {
      return {
        name: [{required: true, message: "请填写名称"}],
        corpId: [{required: true, message: "请填写企业微信ID"}],
        corpAddressBookSecret: [{required: true, message: "请填写企业微信通讯录SECRET"}],
        corpAeskey: [{required: true, message: "请填写企业微信AESKEY"}],
        corpAgentId: [{required: true, message: "请填写企业微信AGENTID"}],
        corpSecret: [{required: true, message: "请填写企业微信SECRET"}],
        corpToken: [{required: true, message: "请填写企业微信TOKEN"}],
        miniappAppid: [{required: true, message: "请填写小程序APPID"}],
        miniappSecret: [{required: true, message: "请填写小程序SECRET"}],
        dvcpUrl: [{required: true, message: "请填写访问域名"}],
        status: [{required: true, message: "请选择状态", trigger: "change"}],
        areaId: [{required: true, message: "请选择地区", trigger: "change"}],
        lat: [{required: true, message: "请选择中心点"}],
      }
    },
  },
  data() {
    return {
      page: {current: 1, size: 10, total: 0},
      dialog: false,
      showMap: false,
      map: null,
      placeSearch: null,
      placeDetail: {},
      searchPlace: "",
      dialogForm: {},
      tableData: [],
      search: {
        name: ""
      },
      sysInfo: {},
      sysInfoDialog: false
    }
  },
  methods: {
    selectMap() {
      Object.keys(this.placeDetail).map(e => this.dialogForm[e] = this.placeDetail[e]);
      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],
          center: [116.394681, 39.910283],
          zoom: 11
        })
        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()
      }
    },
    onChange(row) {
      this.instance.post(`/app/appdvcpconfig/setStatus`, null, {
        params: {
          id: row.id,
          status: row.status
        }
      }).then((res) => {
        if (res.code == 0) {
          this.$message.success(+row.status ? '已启用' : '已禁用');
          this.getTableData();
        }
      })
    },
    add() {
      this.dialogForm = {};
      this.dialog = true;
    },
    del(row) {
      this.$confirm("是否要删除？").then(_ => {
        this.instance.post("/app/appdvcpconfig/delete", null, {
          params: {
            ids: row.id
          }
        }).then(res => {
          if (res.code == 0) {
            this.$message.success("删除成功");
            this.dialog = false;
            this.getTableData();
          }
        })
      })
    },
    detail(row) {
      this.instance.post("/app/appdvcpconfig/detail", null, {
        params: {
          id: row.id
        }
      }).then(res => {
        if (res && res.data) {
          this.dialogForm = {...res.data};
          this.dialog = true;
        }
      })
    },
    getTableData() {
      this.instance.post("/app/appdvcpconfig/list", null, {
        params: {...this.page, ...this.search}
      }).then(res => {
        if (res?.data) {
          this.tableData = res.data?.records
          this.page.total = res.data.total
        }
      })
    },
    confirm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.instance.post("/app/appdvcpconfig/addOrUpdate", {
            ...this.dialogForm,
          }).then(res => {
            if (res.code == 0) {
              this.$message.success(this.dialogForm.id ? "修改成功" : "新增成功");
              this.dialog = false;
              this.getTableData();
            }
          })
        }
      })
    },
    handleSystemInfo(id) {
      this.sysInfoDialog = true
      this.getSystemInfo(id)
    },
    getSystemInfo(id) {
      this.instance.post("/app/appdvcpconfig/getSystemInfo", null, {
        params: {id}
      }).then(res => {
        if (res?.data) {
          this.sysInfo = JSON.parse(res.data)
          this.sysInfo.id = id
        }
      })
    },
    submitSystemInfo() {
      let {id} = this.sysInfo
      this.instance.post("/app/appdvcpconfig/updateSystemInfo", this.sysInfo, {params: {id}}).then(res => {
        if (res?.code == 0) {
          this.$message.success("提交成功!")
          this.sysInfoDialog = false
        }
      })
    }
  },
  created() {
    this.dict.load("integralRuleStatus").then(this.getTableData);
  }
}
</script>

<style lang="scss" scoped>
.AppQyWxConfig {
  height: 100%;


  ::v-deep .mapDialog {
    .el-dialog__body {
      padding: 0;

      .ai-dialog__content {
        padding: 0;
      }

      .ai-dialog__content--wrapper {
        padding: 0 !important;
        position: relative;
      }

      #map {
        width: 100%;
        height: 500px;
      }

      .searchPlaceInput {
        position: absolute;
        width: 250px;
        top: 30px;
        left: 25px;
      }

      #searchPlaceOutput {
        position: absolute;
        width: 250px;
        left: 25px;
        height: initial;
        top: 80px;
        background: white;
        z-index: 250;
        max-height: 300px;
        overflow-y: auto;

        .auto-item {
          text-align: left;
          font-size: 14px;
          padding: 8px;
          box-sizing: border-box;
        }
      }

    }
  }

}
</style>
