<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="120px"
      >
        <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 v-if="addParentForm.type === 2">
        <el-button style="margin-bottom: 10px" type="primary" size="small" @click="hasShowTable">新增</el-button>
        <zj-table
          ref="tableEl"
          :is-drop="true"
          :columns="columns"
          :table-data="tableData"
          :table-attributes="{
            border: true
          }"
        />
      </div>
      <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="120px"
      >
        <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 v-if="addChildForm.type === 2">
        <el-button style="margin-bottom: 10px" type="primary" size="small" @click="hasShowTable">新增</el-button>
        <zj-table
          ref="tableEl"
          :is-drop="true"
          :columns="columns"
          :table-data="tableData"
          :table-attributes="{
            border: true
          }"
        />
      </div>
      <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="100px">
        <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>
      <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,
        flag: '',
        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' }],
        flag: [{ required: true, message: '请选择所属', trigger: 'blur' }]
      },
      editChildId: null,
      addChildFormType: 'add',
      addChildFormVisible: false,
      addChildForm: {
        oneMenu: '',
        twoMenu: '',
        code: '',
        url: '',
        fullUrl: '',
        icon: '',
        sort: 0,
        flag: '',
        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' }],
        flag: [{ required: true, message: '请选择所属', trigger: 'blur' }]
      },
      isChooseIconDialog: false,
      iconList: iconList,
      chooseIconType: null,
      menuTypeList: [
        {
          label: 1,
          value: '目录'
        },
        {
          label: 2,
          value: '页面'
        },
        {
          label: 4,
          value: '外链'
        }
      ],
      tableData: [],
      dialogVisible: false,
      formData: {
        code: '',
        moduleName: '',
      },
      formDataRules: {
        code: [{ required: true, message: '请选择类型', trigger: 'blur' }],
        moduleName: [{ required: true, message: '请选择类型', trigger: 'blur' }]
      },
      operateType: null
    }
  },
  computed: {
    ...mapGetters(['userid', 'name']),
    isAdmin() {
      const type = JSON.parse(localStorage.getItem('supply_user')).type
      return type === 2
    },
    columns() {
      return [
        {
          columnAttributes: {
            label: '名称',
            prop: 'moduleName'
          }
        },
        {
          columnAttributes: {
            label: 'code',
            prop: 'code'
          }
        },
        {
          columnAttributes: {
            label: '操作',
            prop: ''
          },
          render: (h, { row, column, $index }) => {
            return (
              <div style="padding-left:10px">
                <el-button
                  size="mini"
                  type="text"
                  onClick={() => {
                    getMenuDetail({ moduleId: row.moduleId }).then(res => {
                      this.formData = {
                        ...this.formData,
                        ...res.data
                      }
                      this.dialogVisible = true
                    })
                  }}
                >
                  编辑
                </el-button>
                <el-popconfirm
                  title="确定删除吗？"
                  onConfirm={() => {
                    deleteMenu({ id: row.moduleId }).then(res => {
                      this.$successMsg('删除成功')
                      getMenuDetail({ moduleId: this.operateType === 1 ? this.editParentId : this.editChildId }).then(
                        res => {
                          this.tableData = res.data.childList
                        }
                      )
                    })
                  }}
                >
                  <el-button slot="reference" type="text" size="mini">
                    删除
                  </el-button>
                </el-popconfirm>
              </div>
            )
          }
        }
      ]
    }
  },
  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 = []
          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,
            flag: res.data.flag,
            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,
            flag: this.addParentForm.flag,
            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,
            flag: res.data.flag,
            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,
          }
          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: '',
      }
    },
    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,
              flag: this.addChildForm.flag,
              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,
              flag: this.addChildForm.flag,
              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>
