<template>
  <ai-list class="list" v-loading="isLoading">
    <ai-title slot="title" title="导航配置" isShowBottomBorder></ai-title>
    <template slot="content">
      <ai-card title="首页功能">
        <template #right>
          <el-button size="small" type="primary" @click="eidt">{{ isEdit ? '退出编辑' : '编辑' }}</el-button>
          <el-button size="small" @click="save" v-if="isEdit">保存</el-button>
        </template>
        <div slot="content" class="item-wrapper">
          <draggable
            v-model="picked"
            :animation="340"
            group="select"
            style="display: flex;"
            handle=".mover">
            <div class="item" :class="[isEdit ? 'mover' : '']" v-for="(item, i) in picked" :key="i">
              <img :src="item.pictureUrl">
              <i class="el-icon-remove icon" @click="removeChoose(i)" v-if="isEdit"></i>
              <h2>{{ item.name }}</h2>
            </div>
          </draggable>
          <ai-empty style="width: 100%" v-if="!picked.length"></ai-empty>
        </div>
      </ai-card>
      <ai-card title="全部功能">
        <template #right>
          <el-button size="small" type="primary" @click="isShowAdd = true">新增应用</el-button>
          <el-button size="small" type="danger" @click="isEdit = false, isRemove = !isRemove">{{ isRemove ? '取消删除' : '删除应用' }}</el-button>
        </template>
        <div class="all" slot="content">
          <div class="item-row" v-for="(group, index) in list" :key="index">
            <h2>{{ group.name }}</h2>
            <div class="item-wrapper" v-if="isRest">
              <div class="item" v-for="(item, i) in group.list" :key="i">
                <img :src="item.pictureUrl">
                <i class="el-icon-error icon" @click="removeApp(item.id)" v-if="isRemove && item.type !== '0' && item.picked !== '1'"></i>
                <i class="el-icon-circle-plus icon" @click="addApp(item)" v-if="isCanAdd(item)"></i>
                <h2>{{ item.name }}</h2>
                <div class="item-setting">
                  <div class="item-mask"></div>
                  <div class="item-wrapper__icon" @click.stop="editApp(item)">
                    <i class="el-icon-setting"></i>
                    <div>编辑</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <ai-empty style="width: 100%" v-if="!list.length"></ai-empty>
        </div>
      </ai-card>
      <ai-dialog
        :visible.sync="isShowAdd"
        width="780px"
        height="580px"
        :title="id ? '添加专题' : '编辑专题'"
        @close="onClose"
        @onConfirm="onConfirm">
        <el-form ref="form" :model="form" label-width="110px" label-position="right">
          <div class="ai-form" :model="form" label-width="110px" label-position="right">
            <el-form-item label="应用名称" prop="name" style="width: 100%;" :rules="[{ required: true, message: '请输入应用名称', trigger: 'blur' }]">
              <el-input size="small" :maxlength="8" placeholder="请输入应用名称" v-model="form.name"></el-input>
            </el-form-item>
            <el-form-item label="应用模块" style="width: 100%;" prop="menuType" :rules="[{ required: true, message: '请选择应用模块', trigger: 'change' }]">
              <ai-select
                v-model="form.menuType"
                :selectList="dict.getDict('homeConfigMenuType')"
                @change="onChange"
                laceholder="请选择应用模块">
              </ai-select>
            </el-form-item>
            <el-form-item label="认证类型" style="width: 100%;" prop="checkType">
              <ai-select
                v-model="form.checkType"
                :selectList="dict.getDict('miniConfigCheckType')"
                laceholder="请选择认证类型">
              </ai-select>
            </el-form-item>
            <el-form-item label="应用类型" style="width: 100%;" prop="type" :rules="[{ required: true, message: '请选择应用类型', trigger: 'change' }]">
              <ai-select
                v-model="form.type"
                :selectList="typeDict"
                @change="onChange"
                laceholder="请选择应用类型">
              </ai-select>
            </el-form-item>
            <el-form-item label="小程序appid" prop="appId" style="width: 100%;" v-if="form.type === '1'" :rules="[{ required: true, message: '请输入小程序appid', trigger: 'blur' }]">
              <el-input size="small" placeholder="请输入小程序appid" v-model="form.appId"></el-input>
            </el-form-item>
            <el-form-item label="链接" prop="url" style="width: 100%;" v-if="form.type === '2'" :rules="[{ required: true, message: '请输入链接', trigger: 'blur' }]">
              <el-input size="small" placeholder="请输入链接" v-model="form.url"></el-input>
            </el-form-item>
            <el-form-item label="小程序路径" prop="modulePath" style="width: 100%;" v-if="form.type === '3'" :rules="[{ required: true, message: '请输入小程序路径', trigger: 'blur' }]">
              <el-input size="small" placeholder="请输入小程序路径" v-model="form.modulePath"></el-input>
            </el-form-item>
            <el-form-item label="客服链接" prop="url" style="width: 100%;" v-if="form.type === '4'" :rules="[{ required: true, message: '请输入客服链接地址', trigger: 'blur' }]">
              <el-input size="small" placeholder="请输入客服链接地址" v-model="form.url"></el-input>
            </el-form-item>
            <el-form-item label="图标" prop="pictureUrl" style="width: 100%;" :rules="[{ required: true, message: '请上传图标 ', trigger: 'change' }]">
              <ai-uploader v-model="form.pictureUrl" :instance="instance" :limit="1"></ai-uploader>
            </el-form-item>
            <!-- <el-form-item label="权限配置" v-if="form.type === '0'" prop="pictureUrl" style="width: 100%;">
              <el-input disabled :value="girdName" size="small" placeholder="请选择地区">
                <template slot="append">
                  <el-button size="small" @click="isShowArea = true">选择地区</el-button>
                </template>
              </el-input>
            </el-form-item> -->
          </div>
        </el-form>
      </ai-dialog>
      <ai-dialog
        title="选择权限"
        :visible.sync="isShowArea"
        :destroyOnClose="true"
        @close="isShowArea = false"
        @onConfirm="getCheckedTree"
        width="720px">
        <el-tree
          :data="treeList"
          :props="defaultProps"
          node-key="id"
          check-strictly
          ref="tree"
          show-checkbox 
          :default-checked-keys="defaultChecked"
          :default-expanded-keys="defaultExpanded"
          default-expand-all>
        </el-tree>
      </ai-dialog>
    </template>
  </ai-list>
</template>

<script>
  import draggable from 'vuedraggable'
  export default {
    name: 'List',

    props: {
      instance: Function,
      dict: Object
    },

    components: {
      draggable
    },

    data () {
      return {
        picked: [],
        id: '',
        isEdit: false,
        isRemove: false,
        defaultExpanded: [],
        isRest: true,
        isShowArea: false,
        isLoading: false,
        defaultProps: {
          children: "children",
          label: "label",
        },
        treeList: [],
        form: {
          type: '',
          pictureUrl: [],
          url: '',
          name: '',
          checkType: '',
          appId: '',
          modulePath: ''
        },
        typeDict: [{
          dictName: '外链小程序',
          dictValue: '1'
        }, {
          dictName: '外链h5',
          dictValue: '2'
        }, {
          dictName: '新闻',
          dictValue: '3'
        }, {
          dictName: '客服',
          dictValue: '4'
        }],
        info: {},
        isShowAdd: false,
        list: [],
        defaultChecked: []
      }
    },

    created () {
      this.dict.load('homeConfigMenuType', 'miniConfigCheckType').then(() => {
        this.getList()
      })
    },

    methods: {
      getList () {
        this.instance.post(`/app/appminihomeconfig/listAll`).then(res => {
          if (res.code == 0) {
            this.picked = res.data.picked
            this.list = Object.keys(res.data.all).map(item => {
              return {
                name: this.dict.getLabel('homeConfigMenuType', item),
                list: res.data.all[item]
              }
            })
          }
        })
      },

      getCheckedTree () {
        const keys = this.$refs.tree.getCheckedNodes(false, true).map(v => v.id)

        this.instance.post(`/app/appminihomeconfig/addOrUpdate`, {
          ...this.info,
          areaIds: keys
        }).then(res => {
          if (res.code === 0) {
            this.$message.success('修改成功')
            this.isShowArea = false

            this.getList()
          }
        })
      },

      format (list) {
        return list.map(item => {
          if (item.girdLevel !== '2') {
            item.disabled = true
          }

          if (item.girdList && item.girdList.length) {
            item.girdList = this.format(item.girdList)
          }

          return item
        })
      },

      editApp (e) {
        if (e.type !== '0') {
          this.form = {
            ...e,
            pictureUrl: [{
              url: e.pictureUrl
            }]
          }
          this.isShowAdd = true

          return false
        }
        

        this.info = e
        this.isLoading = true
        this.instance.post(`/app/appminihomeconfig/queryDetailById?id=${e.id}`).then(res => {
          if (res.code === 0) {
            let parent = res.data.areaConfigs.map(v => {
              v.label = v.name
              v.children = []

              return v
            }).filter(e => !e.parentId)[0]
            this.defaultExpanded = res.data.areaConfigs.filter(v => v.checked).map(v => v.id)
            this.defaultChecked = res.data.areaConfigs.filter(v => v.checked).map(v => v.id)
            this.addChild(parent, res.data.areaConfigs)
            this.treeList = [parent]

            this.isShowArea = true
          }

          this.isLoading = false
        }).catch(() => {
          this.isLoading = false
        })
      },

      addChild(parent, list) {
        for (let i = 0; i < list.length; i++) {
          if (list[i].parentId === parent.id) {
            parent.children.push(list[i])
          }
        }

        if (list.length > 0) {
          parent['children'].map(v => this.addChild(v, list))
        }
      },

      isCanAdd (item) {
        const isHas = this.picked.map(v => v.id).indexOf(item.id) > -1

        return this.isEdit && item.picked !== '1' && !isHas
      },

      addApp (e) {
        if (this.picked.length >= 8) {
          return this.$message.error('导航功能最多放置8个')
        }

        this.isRemove = false
        this.picked.push(e)
      },

      eidt () {
        if (this.isEdit) {
          this.$confirm('确定退出编辑？').then(() => {
            this.isEdit = false

            this.getList()
          })

          return false
        }
        this.isEdit = !this.isEdit
      },

      removeChoose (index) {
        this.picked.splice(index, 1)

        this.isRest = false

        this.$nextTick(() => {
          this.isRest = true
        })
      },

      save () {
        this.instance.post(`/app/appminihomeconfig/updatePick?ids=${this.picked.map(v => v.id).join(',')}`).then(res => {
          if (res.code === 0) {
            this.$message.success('保存成功')
            this.isEdit = false
            this.isRemove = false

            this.getList()
          }
        })
      },

      onClose () {
        this.form.type = ''
        this.form.pictureUrl = []
        this.form.url = ''
        this.form.name = ''
        this.form.appId = ''
        this.form.checkType = ''
      },

      onChange () {
        this.form.url = ''
        this.form.appId = ''
      },

      onConfirm () {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.instance.post(`/app/appminihomeconfig/addOrUpdate`, {
              ...this.form,
              pictureUrl: this.form.pictureUrl[0].url
            }).then(res => {
              if (res.code === 0) {
                this.$message.success('添加成功')
                this.isShowAdd = false

                this.getList()
              }
            })
          }
        })
      },

      removeApp (id) {
        this.$confirm('确定删除该数据？').then(() => {
          this.instance.post(`/app/appminihomeconfig/delete?ids=${id}`).then(res => {
            if (res.code == 0) {
              this.$message.success('删除成功！')
              this.isRemove = false
              this.getList()
            }
          })
        })
      },

      remove (id) {
        this.$confirm('确定删除该数据？').then(() => {
          this.instance.post(`/app/appapplicationinfo/delete?ids=${id}`).then(res => {
            if (res.code == 0) {
              this.$message.success('删除成功！')
              this.getList()
            }
          })
        })
      }
    }
  }
</script>

<style scoped lang="scss">
  .list {
    ::v-deep .ai-list__content {
      padding: 0!important;

      .ai-list__content--right-wrapper {
        background: transparent!important;
        box-shadow: none!important;
        margin: 0!important;
        padding: 12px 0 12px!important;
      }
    }

    .all {
      .item-row {
        display: flex;

        & > h2 {
          margin-right: 40px;
          font-weight: 500;
          font-size: 16px;
        }
      }
    }

    .item-wrapper {
      display: flex;
      flex-wrap: wrap;
      flex: 1;
      margin-bottom: 20px;

      .icon {
        position: absolute;
        top: 0;
        right: 0;
        z-index: 11;
        font-size: 24px;
        color: red;
        transform: translate(50%, -20%);

        &:hover {
          opacity: 0.6;
          cursor: pointer;
        }
      }

      .item {
        position: relative;
        margin: 0 16px 16px 0;
        text-align: center;
        cursor: pointer;

        .item-setting {
          position: absolute;
          top: 0;
          left: 0;
          z-index: 0;
          opacity: 0;
          width: 100%;
          height: 100%;
          transition: all ease 0.3s;

          .item-wrapper__icon {
            position: relative;
            z-index: 1;
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-direction: column;

            div {
              margin-top: 6px;
              font-size: 16px;
            }
          }

          i, div {
            font-size: 16px;
            color: #fff;
          }

          .item-mask {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.6);
          }

          &:hover {
            z-index: 1;
            opacity: 1;
          }
        }

        img {
          width: 60px;
          height: 60px;
          border-radius: 50%;
        }

        h2 {
          font-weight: normal;
          font-size: 14px;
          color: #666;
        }
      }
    }
  }
</style>
