<template>
  <div class="AppWxcpAppSet">
    <ai-list>
      <template slot="title">
        <ai-title title="企微应用配置" :isShowBottomBorder="false" :isShowArea="false"></ai-title>
      </template>
      <template slot="content">
        <ai-search-bar>
          <template slot="left">
            <el-button type="primary" icon="iconfont iconAdd" size="small" @click="add({}, '添加')">添加</el-button>
          </template>
          <template slot="right">
            <el-input v-model="search.title" size="small" placeholder="搜索标题" clearabl v-throttle="() => {page.current = 1, getList()}"
              @clear=";(page.current = 1), (search.title = ''), getList()" suffix-icon="iconfont iconSearch"/>
          </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 label="banner封面" align="left" width="150" slot="banner">
            <template slot-scope="{ row }">
              <img :src="row.banner" alt="" class="banner-img" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="200" slot="option">
            <template slot-scope="{ row }">
              <el-button type="text" @click="add(row, '编辑')">编辑</el-button>
              <el-button type="text" @click="remove(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </ai-table>
      </template>
    </ai-list>
    <ai-dialog :title="dialog.title" :visible.sync="visible" @onCancel="visible = false" @onConfirm="addConfirm" width="800px">
      <el-form ref="ruleForm" :model="dialogInfo" :rules="formRules" size="small" label-width="120px">
        <el-form-item label="banner封面" prop="banner">
          <ai-uploader v-model="dialogInfo.bannerList" @change="changeBanner" :instance="instance" :limit="1"></ai-uploader>
        </el-form-item>
        <el-form-item label="主页名称" prop="title">
          <el-input placeholder="请输入主页名称" :maxlength="10" show-word-limit v-model="dialogInfo.title"></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-title-flex"> 
        <h3>应用列表</h3>
        <span @click="addMiniApp({}, true, '')">添加</span>
      </div>
      <ai-table :tableData="dialogInfo.wxApplicationList" :colConfigs="miniAppColConfigs" :isShowPagination="false">
        <el-table-column label="icon图片" width="80" slot="icon">
          <template slot-scope="{ row }">
            <img :src="row.icon" alt="" class="banner-img" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="250" slot="option">
          <template slot-scope="{ row }">
             <el-button type="text" @click="top(row)" v-if="row.showIndex > 1">上移</el-button>
              <el-button type="text" @click="next(row)" v-if="row.showIndex < dialogInfo.wxApplicationList.length">下移</el-button>
            <el-button type="text" @click="addMiniApp(row, false, row.$index)">编辑</el-button>
            <el-button type="text" @click="removeMiniApp(row)">删除</el-button>
          </template>
        </el-table-column>
      </ai-table>
    </ai-dialog>
    <ai-dialog title="应用" :visible.sync="miniAppDialog" width="800px" @onCancel="miniAppDialog = false" @onConfirm="addMiniAppConfirm" >
      <el-form ref="miniApppRuleForm" :model="miniAppInfo" :rules="miniAppFormRules" size="small" label-width="120px">
        <el-form-item label="icon图片" prop="icon">
          <ai-uploader v-model="miniAppInfo.iconList" @change="changeIcon" :instance="instance" :limit="1"></ai-uploader>
        </el-form-item>
        <el-form-item label="应用名称" prop="title">
          <el-input placeholder="请输入应用名称" :maxlength="10" show-word-limit v-model="miniAppInfo.title"></el-input>
        </el-form-item>
        <el-form-item label="页面路径" prop="accessPath">
          <el-input placeholder="请输入页面路径" :maxlength="50" show-word-limit v-model="miniAppInfo.accessPath"></el-input>
        </el-form-item>
      </el-form>
    </ai-dialog>
  </div>
</template>

<script>
import {mapState} from 'vuex'

export default {
  label: '企微应用配置',
  name: 'AppWxcpAppSet',
  props: {
    instance: Function,
    dict: Object,
    permissions: Function,
  },
  data() {
    return {
      search: {
        title: '',
      },
      tableData: [],
      page: {
        size: 10,
        current: 1,
        total: 0,
      },
      visible: false,
      dialog: {
        title: '',
      },
      dialogInfo: {},
      formRules: {
        banner: [{required: true, message: '请添加banner封面', trigger: 'blur'}],
        title: [{required: true, message: '请输入主页名称', trigger: 'blur'}],
      },
      colConfigs: [
        {prop: 'banner', label: 'banner封面', slot: 'banner'},
        {prop: 'title', label: '主页名称', width: 150},
        {prop: 'id', label: '配置id', width: 300},
        {prop: 'appNames', label: '应用列表'},
        {slot: 'option', label: '操作', width: 200},
      ],
      miniAppColConfigs: [
        {prop: 'showIndex', label: '序号', width: 80, align: 'center'},
        {prop: 'icon', label: 'icon图片', slot: 'icon', align: 'center'},
        {prop: 'title', label: '应用名称',},
        {prop: 'accessPath', label: '页面路径'},
        {slot: 'option', label: '操作', align: 'center'},
      ],
      miniAppFormRules: {
        icon: [{required: true, message: '请添加icon图片', trigger: 'blur'}],
        title: [{required: true, message: '请输入应用名称', trigger: 'blur'}],
        accessPath: [{ required: true, message: '请输入页面路径', trigger: 'blur' }]
      },
      miniAppDialog: false,
      miniAppInfo: {},
      isAddMiniApp: false,
      editMiniIndex: '',
    }
  },
  computed: {
    ...mapState(['user']),
  },
  created() {
    this.getList()
  },
  mounted() {
  },
  methods: {
    add(row, title) {
      this.dialog.title = title
      this.visible = true
      if(row && row.id) {
        this.instance.post(`/app/appwxapplication/queryDetailById?id=${row.id}`).then(res => {
          if (res?.code == 0) {
            this.dialogInfo = res.data
            this.dialogInfo.bannerList = [{url: this.dialogInfo.banner}]
            this.dialogInfo.wxApplicationList = this.dialogInfo.wxApplicationList || []
          }
        })
      }else {
        this.dialogInfo = {}
        this.dialogInfo.wxApplicationList = []
      } 
    },
    addConfirm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.instance.post(`/app/appwxapplication/addOrUpdate`, {...this.dialogInfo}).then(res => {
            if (res?.code == 0) {
              this.$message.success('新增成功')
              this.visible = false
              this.getList()
            }
          })
        }
      })
    },
    remove(id) {
      this.$confirm('删除后不可恢复，是否要删除该配置？', {
        type: 'error',
      }).then(() => {
        this.instance.post(`/app/appwxapplication/delete?ids=${id}`).then((res) => {
          if (res.code == 0) {
            this.$message.success('删除成功！')
            this.getList()
          }
        })
      })
    },
    addMiniApp(row, isAddMiniApp, index) {
      this.miniAppInfo = row || {}
      if(this.miniAppInfo.icon) {
        this.miniAppInfo.iconList = [{url: this.miniAppInfo.icon}]
        this.editMiniIndex = index
      }
      this.miniAppDialog = true
      this.isAddMiniApp = isAddMiniApp
    },
    removeMiniApp(row) {
      this.$confirm('删除后不可恢复，是否要删除该应用？', {
        type: 'error',
      }).then(() => {
        var showIndex = row.showIndex
        this.dialogInfo.wxApplicationList.map((item) => {
          if(item.showIndex > showIndex) {
            item.showIndex = item.showIndex - 1
          }
        })
        this.dialogInfo.wxApplicationList.splice(row.showIndex-1, 1)
      })
    },
    addMiniAppConfirm() {
      this.$refs.miniApppRuleForm.validate((valid) => {
        if (valid) {
          if(this.isAddMiniApp) { //新增
            this.miniAppInfo.showIndex = this.dialogInfo.wxApplicationList.length + 1
            this.dialogInfo.wxApplicationList.push(this.miniAppInfo)
          }else {
            this.dialogInfo.wxApplicationList[this.editMiniIndex] = this.miniAppInfo
          }
          this.miniAppDialog = false
        }
      })
    },
    top(row) {
      var list = JSON.parse(JSON.stringify(this.dialogInfo.wxApplicationList))
      var oldRow = list[row.showIndex - 2]
      oldRow.showIndex ++
      row.showIndex --
      list[row.showIndex - 1] = row
      list[row.showIndex] = oldRow
      this.$set(this.dialogInfo, 'wxApplicationList', list)
    },
    next(row) {
      var list = JSON.parse(JSON.stringify(this.dialogInfo.wxApplicationList))
      var oldRow = list[row.showIndex]
      oldRow.showIndex --
      row.showIndex ++
      list[row.showIndex-1] = row
      list[oldRow.showIndex-1] = oldRow
      this.$set(this.dialogInfo, 'wxApplicationList', list)
    },
    changeBanner(e) {
      this.dialogInfo.bannerList = e
      this.dialogInfo.banner = e[0].url
    },
    changeIcon(e) {
      this.miniAppInfo.iconList = e
      this.miniAppInfo.icon = e[0].url
    },
    getList() {
      this.instance.post(`/app/appwxapplication/list`, null, {
        params: {
          ...this.search,
          ...this.page,
        },
      })
      .then((res) => {
        if (res.code == 0) {
          res.data.records.map((item) => {
            item.appNames = ''
            item.wxApplicationList.map((app, index) => {
              if(index == 0) {
                item.appNames = app.title
              }
              if(index > 0) {
                item.appNames = item.appNames + `,${app.title}`
              }
            })
          })
          this.tableData = res.data.records

          this.page.total = res.data.total
        }
      })
      .catch(() => {
      })
    },
  },
}
</script>

<style lang="scss">
.AppWxcpAppSet {
  height: 100%;
  // padding: 15px 10px;
  .banner-img {
    width: 50px;
    height: 50px;
  }
  .dialog-title-flex{
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;
    h3{
      font-size: 16px;
      color: #333;
    }
    span{
      color: #26f;
      cursor: pointer;
    }
  }
}
</style>
