<template>
  <div class="app-container">
    <div class="mymain-container">
      <div class="btn-group clearfix">
        <div class="fl">
          <el-button size="small" type="primary" icon="el-icon-plus" @click="addOrEditParent('add')"
            >添加菜单</el-button
          >
        </div>
      </div>
      <div class="table">
        <el-table
          v-loading="listLoading"
          :data="dataList"
          row-key="moduleId"
          border
          default-expand-all
          :tree-props="{ children: 'pages' }"
        >
          <el-table-column prop="moduleName" label="菜单名称" min-width="150" />
          <el-table-column prop="url" label="菜单URL" min-width="150" />
          <el-table-column prop="fullUrl" label="菜单全URL" min-width="200" />
          <el-table-column align="center" prop="icon" label="菜单图标">
            <template slot-scope="scope">
              <i :class="scope.row.icon" style="font-size: 18px" />
            </template>
          </el-table-column>
          <el-table-column align="center" prop="status" label="状态">
            <template slot-scope="scope">
              <span>{{ ['显示', '不显示'][[true, false].indexOf(scope.row.status)] || '' }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="isCache" label="状态">
            <template slot-scope="scope">
              <span>{{ ['缓存', '不缓存'][[1,0].indexOf(scope.row.isCache)] || '' }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="sortNum" label="排序" />
          <el-table-column align="right" label="操作" width="150" fixed="right">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-plus"
                @click="addOrEditChild('add', scope.row.moduleId)"
              />
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-edit"
                @click="addOrEditChild('edit', scope.row.moduleId)"
              />
              <el-popconfirm style="margin-left: 10px" title="确定删除吗？" @confirm="handleDelete(scope.row.moduleId)">
                <el-button slot="reference" size="mini" icon="el-icon-delete" />
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 新增编辑 一级菜单 -->
    <el-dialog
      :title="addParentFormType == 'add' ? '添加一级菜单' : '编辑一级菜单'"
      :visible.sync="addParentFormVisible"
      :show-close="false"
      width="60%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="addParentForm"
        :model="addParentForm"
        :rules="addParentFormRules"
        label-position="left"
        label-width="140px"
      >
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="addParentForm.type">
            <el-radio v-for="item in menuTypeList" :key="item.label" :label="item.label">
              {{ item.value }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="一级菜单" prop="oneMenu">
          <el-input v-model="addParentForm.oneMenu" type="text" placeholder="请输入一级菜单名称" show-word-limit />
        </el-form-item>
        <el-form-item label="CODE" prop="code">
          <el-input v-model="addParentForm.code" placeholder="请输入CODE" />
        </el-form-item>
        <el-form-item label="URL" prop="url">
          <el-input v-model="addParentForm.url" placeholder="请输入URL" />
        </el-form-item>
        <el-form-item label="全URL" prop="fullUrl">
          <el-input v-model="addParentForm.fullUrl" placeholder="请输入全URL" />
        </el-form-item>
        <el-form-item label="图标">
          <div class="iconInput">
            <div v-if="addParentForm.icon" class="icon"><i :class="addParentForm.icon" /></div>
            <el-input v-model="addParentForm.icon" placeholder="请选择图标" />
            <el-button type="primary" @click="toChooseIcon(1)">选择</el-button>
          </div>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model.number="addParentForm.sort" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="是否显示" prop="status">
          <el-switch
            v-model="addParentForm.status"
            :active-value="true"
            :inactive-value="false"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </el-form-item>
        <el-form-item label="是否缓存页面" prop="isCache">
          <el-switch
            v-model="addParentForm.isCache"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAddParentForm">取 消</el-button>
        <el-button type="primary" @click="submitAddParentForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 新增编辑 二级菜单 -->
    <el-dialog
      :title="addChildFormType == 'add' ? '添加二级菜单' : '编辑二级菜单'"
      :visible.sync="addChildFormVisible"
      :show-close="false"
      width="60%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="addChildForm"
        :model="addChildForm"
        :rules="addChildFormRules"
        label-position="left"
        label-width="140px"
      >
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="addChildForm.type">
            <el-radio v-for="item in menuTypeList" :key="item.label" :label="item.label">
              {{ item.value }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上级菜单" prop="oneMenu">
          <el-cascader
            v-model="addChildForm.oneMenu"
            style="width: 100%"
            :options="[{ moduleId: '0', moduleName: '设定一级' }, ...dataList]"
            :props="{ checkStrictly: true, value: 'moduleId', label: 'moduleName' }"
            filterable
            clearable
          />
        </el-form-item>
        <el-form-item label="二级菜单" prop="twoMenu">
          <el-input v-model="addChildForm.twoMenu" type="text" placeholder="请输入二级菜单名称" show-word-limit />
        </el-form-item>
        <el-form-item label="CODE" prop="code">
          <el-input v-model="addChildForm.code" placeholder="请输入CODE" />
        </el-form-item>
        <el-form-item label="URL" prop="url">
          <el-input v-model="addChildForm.url" placeholder="请输入URL" />
        </el-form-item>
        <el-form-item label="全URL" prop="fullUrl">
          <el-input v-model="addChildForm.fullUrl" placeholder="请输入全URL" />
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <div class="iconInput">
            <div v-if="addChildForm.icon" class="icon"><i :class="addChildForm.icon" /></div>
            <el-input v-model="addChildForm.icon" placeholder="请选择图标" />
            <el-button type="primary" @click="toChooseIcon(2)">选择</el-button>
          </div>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model.number="addChildForm.sort" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="是否显示" prop="status">
          <el-switch
            v-model="addChildForm.status"
            :active-value="true"
            :inactive-value="false"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </el-form-item>
        <el-form-item label="是否缓存页面" prop="isCache">
          <el-switch
            v-model="addChildForm.isCache"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAddChildForm">取 消</el-button>
        <el-button type="primary" @click="submitAddChildForm">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="formData.moduleId ? '编辑' : '新增'"
      :visible.sync="dialogVisible"
      :show-close="false"
      width="40%"
      :close-on-click-modal="false"
    >
      <el-form ref="formData" :model="formData" :rules="formDataRules" label-position="left" label-width="140px">
        <el-form-item label="code" prop="code">
          <el-input v-model="formData.code" placeholder="请输入类型" clearable></el-input>
        </el-form-item>
        <el-form-item label="名称" prop="moduleName">
          <el-input v-model="formData.moduleName" placeholder="请输入接口名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="API" prop="apis">
          <el-select v-model="formData.apis" style="width: 100%" placeholder="请选择API" multiple clearable filterable>
            <el-option
              v-for="item in apiList"
              :key="item.id"
              :label="item.tag + '  >  ' + item.operation + '  -  ' + item.url"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          @click="
            dialogVisible = false
            chongzhi()
          "
          >取 消</el-button
        >
        <el-button type="primary" @click="addOperative">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 选择图标 -->
    <el-dialog
      title="选择图标"
      :visible.sync="isChooseIconDialog"
      :show-close="true"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="iconList">
        <div v-for="(item, index) in iconList" :key="index" class="item" @click="chooseIcon(item.value)">
          <i :class="item.value" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
import { getMenuList, addMenu, editMenu, deleteMenu, getMenuDetail } from '@/api/setting'
import iconList from '@/const/iconList.js'
export default {
  data() {
    return {
      baseURL: process.env.VUE_APP_BASE_API,
      myHeaders: { 'x-token': getToken() },
      dataList: [], // 列表数据
      listLoading: true, // 列表加载loading
      screenForm: {
        // 筛选表单数据
        keyword: '' // 关键词
      },
      editParentId: null,
      addParentFormType: 'add',
      addParentFormVisible: false,
      addParentForm: {
        oneMenu: '',
        code: '',
        url: '',
        fullUrl: '',
        icon: '',
        sort: 0,
        type: 1,
        status: true,
        isCache: 1
      },
      addParentFormRules: {
        type: [{ required: true, message: '请选择类型', trigger: 'change' }],
        oneMenu: [{ required: true, message: '请填写一级菜单名称', trigger: 'blur' }],
        code: [{ required: true, message: '请填写菜单CODE', trigger: 'blur' }],
        url: [{ required: true, message: '请填写菜单URL', trigger: 'blur' }],
        icon: [{ required: true, message: '请选择图标', trigger: 'blur' }],
      },
      editChildId: null,
      addChildFormType: 'add',
      addChildFormVisible: false,
      addChildForm: {
        oneMenu: '',
        twoMenu: '',
        code: '',
        url: '',
        fullUrl: '',
        icon: '',
        sort: 0,
        type: 1,
        status: true,
        isCache:1
      },
      addChildFormRules: {
        type: [{ required: true, message: '请选择类型', trigger: 'change' }],

        oneMenu: [{ required: true, message: '请选择一级菜单', trigger: 'change' }],
        twoMenu: [{ required: true, message: '请填写二级菜单', trigger: 'blur' }],
        code: [{ required: true, message: '请填写菜单CODE', trigger: 'blur' }],
        url: [{ required: true, message: '请填写菜单URL', trigger: 'blur' }],
      },
      isChooseIconDialog: false,
      iconList: iconList,
      chooseIconType: null,
      menuTypeList: [
        {
          label: 1,
          value: '目录'
        },
        {
          label: 2,
          value: '页面'
        },
        {
          label: 4,
          value: '外链'
        }
      ],
      tableData: [],
      dialogVisible: false,
      formData: {
        code: '',
        moduleName: '',
        apis: []
      },
      formDataRules: {
        code: [{ required: true, message: '请选择类型', trigger: 'blur' }],
        moduleName: [{ required: true, message: '请选择类型', trigger: 'blur' }]
        // apis: [{ required: true, message: '请选择类型', trigger: 'change' }]
      },
      apiList: [],
      operateType: null
    }
  },
  computed: {
    ...mapGetters(['userid', 'name']),
    isAdmin() {
      const type = JSON.parse(localStorage.getItem('greemall_user')).type
      return type === 2
    },
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getMenuList({
        adminUserId: this.userid,
        flag: 'menu'
      })
        .then(res => {
          this.dataList = this.recursionFn(res.data)
          console.log(this.dataList)
        })
        .finally(() => {
          this.listLoading = false
        })
    },
    recursionFn(arr) {
      if (!arr.length) return
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].children.length) {
          // arr[i].pages 页面级, 页面类型  [1, 2, 4]
          // arr[i].controls 操作级, 操作类型  [3]
          arr[i].pages = []
          arr[i].controls = []
          for (let j = 0; j < arr[i].children.length; j++) {
            if ([1, 2, 4].includes(arr[i].children[j].type)) {
              arr[i].pages.push(arr[i].children[j])
            }
            if ([3].includes(arr[i].children[j].type)) {
              arr[i].controls.push(arr[i].children[j])
            }
          }
          this.recursionFn(arr[i].children)
        }
      }
      return arr || []
    },
    // 打开 新增编辑 一级菜单
    addOrEditParent(type, cid) {
      this.addParentFormType = type
      this.addParentFormVisible = true
      this.operateType = 1
      if (type == 'edit') {
        this.editParentId = cid
        getMenuDetail({ moduleId: cid }).then(res => {
          this.addParentForm = {
            oneMenu: res.data.moduleName,
            code: res.data.code,
            url: res.data.url,
            fullUrl: res.data.fullUrl,
            icon: res.data.icon,
            sort: res.data.sortNum,
            type: res.data.type,
            status: res.data.status,
            isCache: res.data.isCache,
            childList: res.data.childList
          }
        })
      }
    },

    // 取消 新增编辑 一级菜单
    cancelAddParentForm() {
      this.addParentFormVisible = false
      this.tableData = []
      this.$refs.addParentForm.resetFields()
    },

    // 提交 一级菜单
    submitAddParentForm() {
      this.$refs.addParentForm.validate(valid => {
        if (valid) {
          const params = {
            moduleName: this.addParentForm.oneMenu,
            code: this.addParentForm.code,
            url: this.addParentForm.url,
            fullUrl: this.addParentForm.fullUrl,
            icon: this.addParentForm.icon,
            sortNum: this.addParentForm.sort,
            parentId: 0,
            type: this.addParentForm.type,
            status: this.addParentForm.status,
            isCache: this.addParentForm.isCache,
          }
          if (this.addParentFormType == 'edit') {
            params.moduleId = this.editParentId
            editMenu(params).then(res => {
              this.cancelAddParentForm()
              this.getList()
              this.$successMsg('编辑成功')
            })
          } else {
            // params.type = 2;
            addMenu(params).then(res => {
              this.cancelAddParentForm()
              this.getList()
              this.$successMsg('添加成功')
            })
          }
        }
      })
    },

    // 打开 新增编辑 二级菜单
    addOrEditChild(type, cid) {
      this.addChildFormType = type
      this.addChildFormVisible = true
      this.operateType = 2
      if (type == 'add') {
        this.addChildForm.oneMenu = cid
      }

      if (type == 'edit') {
        this.editChildId = cid
        getMenuDetail({ moduleId: cid }).then(res => {
          this.addChildForm = {
            oneMenu: res.data.parentId,
            twoMenu: res.data.moduleName,
            code: res.data.code,
            url: res.data.url,
            fullUrl: res.data.fullUrl,
            icon: res.data.icon,
            sort: res.data.sortNum,
            type: res.data.type,
            status: res.data.status,
            isCache: res.data.isCache,
            childList: res.data.childList
          }
          this.tableData = res.data.childList
        })
      }
    },
    addOperative() {
      this.$refs.formData.validate(valid => {
        if (valid) {
          const params = {
            parentId: this.editChildId,
            moduleId: this.formData.moduleId || '',
            moduleName: this.formData.moduleName,
            code: this.formData.code,
            type: 3,
            childList: this.formData.childList || null,
            apiList: this.formData.apis
          }
          if (this.formData.moduleId) {
            params.parentId = null
            editMenu(params).then(res => {
              this.dialogVisible = false
              this.$successMsg('编辑成功')
              this.chongzhi()
              getMenuDetail({ moduleId: this.operateType === 1 ? this.editParentId : this.editChildId }).then(res => {
                this.tableData = res.data.childList
              })
            })
          } else {
            addMenu(params).then(res => {
              this.dialogVisible = false
              this.$successMsg('添加成功')
              this.chongzhi()
              getMenuDetail({ moduleId: this.operateType === 1 ? this.editParentId : this.editChildId }).then(res => {
                this.tableData = res.data.childList
              })
            })
          }
        }
      })
    },
    chongzhi() {
      this.formData = {
        code: '',
        moduleName: '',
        apis: []
      }
    },
    hasShowTable() {
      this.dialogVisible = true
    },
    // 取消 新增编辑 二级菜单
    cancelAddChildForm() {
      this.addChildFormVisible = false
      this.tableData = []
      this.$refs.addChildForm.resetFields()
    },

    // 提交 二级菜单
    submitAddChildForm() {
      this.$refs.addChildForm.validate(valid => {
        if (valid) {
          let params = {}
          let parentId = null
          if (this.addChildForm.oneMenu instanceof Array) {
            parentId = this.addChildForm.oneMenu[this.addChildForm.oneMenu.length - 1] || 0
          } else {
            parentId = this.addChildForm.oneMenu || 0
          }
          if (this.addChildFormType == 'edit') {
            params = {
              parentId,
              moduleId: this.editChildId,
              moduleName: this.addChildForm.twoMenu,
              code: this.addChildForm.code,
              url: this.addChildForm.url,
              fullUrl: this.addChildForm.fullUrl,
              icon: this.addChildForm.icon,
              sortNum: this.addChildForm.sort,
              type: this.addChildForm.type,
              status: this.addChildForm.status,
              isCache: this.addChildForm.isCache,
            }
            editMenu(params).then(res => {
              this.cancelAddChildForm()
              this.getList()
              this.$successMsg('编辑成功')
            })
          } else {
            params = {
              parentId,
              moduleName: this.addChildForm.twoMenu,
              code: this.addChildForm.code,
              url: this.addChildForm.url,
              fullUrl: this.addChildForm.fullUrl,
              icon: this.addChildForm.icon,
              sortNum: this.addChildForm.sort,
              type: this.addChildForm.type,
              status: this.addChildForm.status,
              isCache: this.addChildForm.isCache,
            }
            addMenu(params).then(res => {
              this.cancelAddChildForm()
              this.getList()
              this.$successMsg('添加成功')
            })
          }
        }
      })
    },

    // 操作 - 删除
    handleDelete(id) {
      deleteMenu({ id: id }).then(res => {
        this.getList()
        this.$successMsg()
      })
    },

    // 去选择图标
    toChooseIcon(type) {
      this.chooseIconType = type
      this.isChooseIconDialog = true
    },

    // 选择图标
    chooseIcon(value) {
      if (this.chooseIconType === 1) {
        this.addParentForm.icon = value
      } else if (this.chooseIconType > 1) {
        this.addChildForm.icon = value
      }
      this.isChooseIconDialog = false
    }
  }
}
</script>

<style scoped lang="scss">
.iconList {
  display: flex;
  flex-wrap: wrap;
  max-height: 40vh;
  overflow-y: scroll;
  .item {
    width: 40px;
    height: 40px;
    text-align: center;
    line-height: 40px;
    cursor: pointer;
    i {
      font-size: 18px;
    }
    &:hover {
      background: #f5f5f5;
      i {
        color: #409eff;
      }
    }
  }
}
.iconInput {
  display: flex;
  .icon {
    margin-right: 10px;
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    box-sizing: border-box;
    color: #606266;
    width: 40px;
    height: 40px;
    text-align: center;
    line-height: 40px;
    flex-shrink: 0;
    i {
      font-size: 18px;
    }
  }
  input {
    flex: 1;
  }
  button {
    margin-left: 10px;
  }
}
</style>

<style lang="scss">
.el-image-viewer__wrapper .el-icon-circle-close {
  color: #ffffff !important;
  font-size: 60px;
}
.el-table__row.expanded {
  background: #f5f5f5;
}

// th {
//   text-align: center !important;
// }
</style>