<template>
  <div>
    <a-modal
      v-if="visible"
      title="快捷菜单管理"
      width="800px"
      :visible="visible"
      :destroy-on-close="true"
      :mask-closable="false"
      @afterClose="saveNav"
      @cancel="saveNav"
    >
      <a-row :class="$style.navConfig">
        <a-col v-if="isskeleton" :span="7">
          <a-skeleton
            active
            :paragraph="{ rows: 8, width: '100%' }"
            :title="false"
            :class="$style.skeleton"
          />
        </a-col>
        <a-col v-else :span="7">
          <a-tree
            v-model="selectorData"
            checkable
            check-strictly
            class="draggable-tree"
            :tree-data="gData"
            :auto-expand-parent="autoExpandParent"
            @check="onCheck"
          >
            <span slot="title" slot-scope="record" :title="record.tooltip || record.text">{{
              record.text
            }}</span>
          </a-tree>
        </a-col>

        <a-col :span="7">
          <a-card title="已选择" size="small" :bordered="false">
            <a-list size="small" :split="false" :loading="loading" :data-source="selectorDataList">
              <a-list-item
                slot="renderItem"
                slot-scope="item, index"
                :class="[$style.navList, selActive === index ? $style.active : '']"
                :title="item.tooltip || item.name"
                @click="selectorClick(item, index)"
              >
                {{ item.name }}

                <a-icon slot="extra" type="sd-trash2" @click.stop="del(item)" />
              </a-list-item>
            </a-list>
          </a-card>
        </a-col>
        <a-col :span="10">
          <a-card title="菜单属性" size="small" :bordered="false">
            <a-form layout="horizontal">
              <a-form-item :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" label="显示名称:">
                <a-input v-model="navName.name" disabled />
              </a-form-item>
              <a-form-item :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" label="图标:">
                <div :class="$style.iconWrap">
                  <sd-icon
                    v-if="navName.icon.name"
                    :type="navName.icon.name"
                    :theme="navName.icon.theme"
                  />
                </div>
                <a-button type="link" @click="openIconConfig">
                  选择图标
                </a-button>
              </a-form-item>
            </a-form>
          </a-card>
        </a-col>
      </a-row>
      <template slot="footer">
        <a-button key="submit" @click="saveNav">
          关闭
        </a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import { Message } from 'ant-design-vue'
import PageService from '@/common/services/page-service'
import pickValues from '@/common/services/pick-values'
import sdIconPickerVue from '@/common/components/sd-icon-picker.vue'
import navMenuService from '../frame/nav-menu-service'
import components from './_import-components/sd-quick-config-import'
export default {
  name: 'SdQuickConfig',

  components,
  props: {
    quicklinks: {
      type: Array,
      default: function() {
        return []
      },
    },
    formId: {
      type: String,
      default: '',
    },
    isSys: {
      type: Boolean,
      default: false,
    },
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      // 展示骨架
      isskeleton: {
        type: Boolean,
        default: true,
      },
      loading: true, // 列表loading
      gData: [], // 导航树数据
      autoExpandParent: true,
      navName: {
        name: '',
        icon: {
          theme: '',
          name: '',
        },
      },
      selectorData: [], // 选中树数据
      selActive: '',
      selectorDataList: [], // 列表数据
      listDatil: {}, // 列表详情
    }
  },
  computed: {
    treeData() {
      return this.handleTreeData(this.flowtreeData, this.targetKeys)
    },
  },
  created() {
    this.detail()
    this.getnavList()
    navMenuService.getUserMenus().then((data) => {
      this.getTreeData(data)
      this.isskeleton = false
      this.gData = data
    })
  },
  mounted() {},
  methods: {
    // 删除导航已选列表
    del(item) {
      if (item.id) {
        const params = {
          ids: item.id,
        }
        if (this.isSys === true) {
          // 管理端
          PageService.delete(params, 'oaPersonalSysQuickMenu').then((res) => {
            this.navName = {
              name: '',
              icon: {
                theme: '',
                name: '',
              },
            }
            Message.success('删除成功')
            this.getnavList()
          })
        } else {
          PageService.delete(params, 'oaPersonalQuickMenu').then((res) => {
            this.navName = {
              name: '',
              icon: {
                theme: '',
                name: '',
              },
            }
            Message.success('删除成功')
            this.getnavList()
          })
        }
      }
    },
    // 获取导航列表
    getnavList() {
      this.loading = true
      if (this.isSys === true) {
        const params = {
          columns: 'name,url,menuId,icon,sortNumber,menuText',
          expressions: [],
          formId: this.formId,
          startPosition: 0,
          maxResults: -1,
        }
        navMenuService.getQuickList(params).then((data) => {
          this.loading = false
          this.selectorDataList = [] // 已选择列表
          this.selectorData = [] // 加载清空，防止累加
          data.data.forEach((item) => {
            item.key = {
              menuId: Number(item.menuId),
            }
            this.selectorData.push(JSON.stringify(item.key))
            this.selectorData = [...this.selectorData]
            const itemObj = {}
            itemObj.name = item.name
            itemObj.menuId = item.menuId
            itemObj.sortNumber = item.sortNumber
            itemObj.icon = item.icon
            itemObj.url = item.url
            itemObj.id = item.id
            itemObj.tooltip = item.menuText
            this.selectorDataList.push(itemObj)
          })
        })
      } else {
        navMenuService.getQuickMenus().then((data) => {
          this.loading = false
          this.selectorDataList = [] // 已选择列表
          this.selectorData = [] // 加载清空，防止累加
          if (data) {
            data.forEach((item) => {
              item.key = {
                menuId: Number(item.menuId),
              }
              this.selectorData.push(JSON.stringify(item.key))
              this.selectorData = [...this.selectorData]
              const itemObj = {}
              itemObj.name = item.name
              itemObj.menuId = item.menuId
              itemObj.sortNumber = item.sortNumber
              itemObj.icon = item.icon
              itemObj.url = item.url
              itemObj.id = item.id
              itemObj.tooltip = item.menuText
              this.selectorDataList.push(itemObj)
            })
          }
        })
      }
    },
    // 获取菜单树数据
    getTreeData(data) {
      let result
      if (!data) {
        return
      }
      // 查到父级去掉复选框
      for (var i = 0; i < data.length; i++) {
        const item = data[i]
        item.key = JSON.stringify({
          menuId: Number(item.menuId),
        })

        // item.key = item.menuId
        if (item.children && item.children.length > 0) {
          item.checkable = false
          result = this.getTreeData(item.children)
        } else {
          item.enabled = false
          // item.disableCheckbox = true
          result = this.getTreeData(item.children)
        }
      }
      return result
    },
    // 勾选复选框获取选中数据
    onCheck(checkedKeys, info) {
      this.selectorData = checkedKeys.checked
      if (this.selectorData.length > 6) {
        Message.error('快捷导航最多只能选取6个！')
        return
      }
      // 为false说明是取消导航选中，执行删除列表，反之新增
      if (info.checked === false) {
        this.selectorDataList.forEach((item) => {
          if (item.menuId === Number(info.node.dataRef.menuId)) {
            this.del(item)
          }
        })
      } else {
        const resJson = this.listDatil
        resJson.pageFormData.pageFieldInfos.forEach((item) => {
          if (item.name === 'icon') {
            item.value = '{"name":"sd-contacts","theme":"twotone"}'
          }
          if (item.name === 'sortNumber') {
            item.value = '1'
          }
          if (item.name === 'name') {
            item.value = info.node.dataRef.title
          }
          if (item.name === 'menuId') {
            item.value = info.node.dataRef.menuId
          }
          if (item.name === 'url') {
            item.value = info.node.dataRef.url
          }
          if (item.name === 'id') {
            item.value = ''
          }
          if (item.name === 'menuText') {
            item.value = info.node.dataRef.tooltip || ''
          }
        })
        const data = {
          eventId: 'save',
          inputs: resJson.pageFormData.pageFieldInfos.map((v) => ({
            name: v.name,
            value: v.value,
          })),
          pageFlowId: resJson.attrs.pageflowId,
          pagePath: resJson.attrs.pagePath,
        }
        navMenuService.saveItem(data).then((res) => {
          Message.success('保存成功')
          this.getnavList()
        })
      }
    },
    // 打开图标库
    openIconConfig() {
      if (this.navName.icon.name) {
        const icon = this.navName.icon
        pickValues(sdIconPickerVue, {
          value: [
            {
              // 加上id属性
              id: `${icon.name}/${icon.theme}`,
              ...icon,
            },
          ],
        }).then((icons) => {
          if (icons) {
            // 取出第一个图标，去掉id属性
            const icon = {
              name: icons[0].name,
              theme: icons[0].theme,
            }
            const resJson = this.listDatil
            resJson.pageFormData.pageFieldInfos.forEach((item) => {
              if (item.name === 'icon') {
                item.value = JSON.stringify(icon)
              }
            })
            const data = {
              eventId: 'save',
              inputs: resJson.pageFormData.pageFieldInfos.map((v) => ({
                name: v.name,
                value: v.value,
              })),
              pageFlowId: resJson.attrs.pageflowId,
              pagePath: resJson.attrs.pagePath,
            }
            navMenuService.saveItem(data).then((res) => {
              this.navName.icon = icon
              Message.success('保存成功')
            })
          }
        })
      } else {
        Message.error('请选择要修改的导航！')
      }
    },
    // 点击已选择
    selectorClick(val, index) {
      this.detail(val.id)
      this.selActive = index
    },
    detail(id) {
      const params = {}
      if (id) {
        params.id = id
      }

      if (this.isSys === true) {
        PageService.get(params, 'personal/quickmenu/oaPersonalSysQuickMenu').then((res) => {
          this.listDatil = res.data
          res.data.pageFormData.pageFieldInfos.forEach((item) => {
            if (item.name === 'icon') {
              if (item.value) {
                this.navName.icon.name = JSON.parse(item.value).name
                this.navName.icon.theme = JSON.parse(item.value).theme
              }
            }
            if (item.name === 'name') {
              this.navName.name = item.value
            }
          })
        })
      } else {
        PageService.get(params, 'personal/quickmenu/oaPersonalQuickMenu').then((res) => {
          this.listDatil = res.data
          res.data.pageFormData.pageFieldInfos.forEach((item) => {
            if (item.name === 'icon') {
              if (item.value) {
                this.navName.icon.name = JSON.parse(item.value).name
                this.navName.icon.theme = JSON.parse(item.value).theme
              }
            }
            if (item.name === 'name') {
              this.navName.name = item.value
            }
          })
        })
      }
    },
    // 保存快捷菜单
    saveNav() {
      if (this.selectorDataList.length > 6) {
        Message.error('快捷导航最多只能选六个')
      } else {
        const saveData = []
        this.selectorDataList.forEach((item) => {
          if (item.icon === '' || item.icon === null) {
            item.icon = 'sd-contacts'
            item.theme = 'twoTone'
          }
          saveData.push(item)
        })
        this.$emit('navDataClick', saveData)
      }
    },
    // 关闭
    handleCancel() {
      this.$emit('handleCancel')
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
$iconfont: 30px;
.nav-config {
  .skeleton {
    width: 60%;
    margin: 6% 0 0 5%;
  }
  .nav-list {
    padding: 4px 12px;
    cursor: pointer;

    &.active {
      color: $white;
      background: $primary-color;
    }
  }
  .icon-wrap {
    display: flex;
    align-items: center;
    justify-content: center;
    float: left;
    width: $iconfont * 2;
    height: $iconfont * 2;
    padding: 8px;
    border: 1px solid #e8e8e8;
    border-radius: 2px;
    :global(.anticon) {
      font-size: $iconfont + 10;
    }
  }
}
</style>
