<template>
  <div class="white pa-3">
    <table-list
      :headers="headers"
      :items="items"
      :total="total"
      :loading="loading"
      :is-tools="false"
      :show-select="false"
      :disable-sort="true"
      :page-info="pageInfo"
      item-key="id"
      @pageHandleChange="pageHandleChange"
    >
      <template v-slot:state="{ item }">
        <v-chip
          :color="state[item.state].color"
          text-color="white"
          small
          label
        >
          {{ state[item.state].label }}
        </v-chip>
      </template>
      <template v-slot:disable="{ item }">
        <!-- <v-btn small :color="item.disable === 'no' ? 'success' : 'error'" @click="handleReject(item.disable, item.id)" class="mr-2">
          {{ item.disable === 'no' ? '已启用' : '已冻结' }}
        </v-btn> -->
        <v-chip
          :color="item.disable === 'no' ? 'success' : 'error'"
          small
          outlined
        >
          {{ item.disable === 'no' ? '已启用' : '已冻结' }}
        </v-chip>
      </template>
      <template v-slot:createdTime="{ item }">
        <span>{{ dateFormat(item.createdTime) }}</span>
      </template>
      <template v-slot:actions="{ item }">
        <v-btn text color="primary" @click="handleDetails(item)" class="mr-2">查看详情</v-btn>
        <!-- <v-btn text color="warning" @click="handleExamine(item.id, item.state)" class="mr-2">编辑审核</v-btn> -->
        <v-btn :disabled="item.state !== 1" text color="primary" @click="handleEditRoles(item)">租户套餐</v-btn>
        <v-btn text :color="item.disable === 'yes' ? 'success' : 'error'" @click="handleReject(item.disable, item.id)" class="mr-2">
          {{ item.disable === 'yes' ? '启用' : '冻结' }}
        </v-btn>
      </template>
    </table-list>
    <edit-dialog title="权限列表" :visible.sync="visible" @submit="handleSave">
      <v-treeview
        v-loading="rolesLoading"
        selectable
        dense
        v-model="selected"
        :items="roles"
        item-disabled="mark"
        item-key="id"
        item-text="label"
      />
        <!-- selection-type="independent" -->
    </edit-dialog>
    <edit-dialog title="审核" :visible.sync="visibleExamine" @submit="handleSaveExamine">
      <form-list :items="formOption" ></form-list>
    </edit-dialog>
    <edit-dialog title="详情" :visible.sync="visibleDetails" :footer="false" widthType="1">
      <v-simple-table dense fixed-header height="500px" >
        <template v-slot:default>
          <thead>
            <tr>
              <th class="text-left">标题</th>
              <th class="text-left">内容</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in desserts" :key="item.key" >
              <td>{{ item.key }}</td>
              <td>{{ item.value }}</td>
            </tr>
          </tbody>
        </template>
      </v-simple-table>
    </edit-dialog>
  </div>
</template>

<script>
import TableList from '@/components/List/table.vue'
import EditDialog from '@/components/Dialog'
import FormList from '@/components/Form/list.vue'
import {
  getCompanyInfoPage,
  companyStateChange,
  getCompanyDetails,
  companyOperateState,
  saveCompanyPackage,
  getRouters
} from '@/api/menu'
import { getUserList } from '@/api/user'
import { dateFormat } from '@/utils/date'
// import cloneDeep from 'lodash/cloneDeep'
export default {
  name: 'menu-tenantry',
  components: { TableList, EditDialog, FormList },
  data () {
    return {
      state: [
        {
          label: '待审核',
          color: 'warning'
        },
        {
          label: '已生效',
          color: 'success'
        },
        {
          label: '已拒绝',
          color: 'error'
        }
      ],
      headers: [
        { text: '公司名称', align: 'start', value: 'name' },
        // { text: '申请人', align: 'start', value: 'homeUserId' },
        { text: '电话', align: 'start', value: 'phone' },
        { text: '地址', align: 'start', value: 'address' },
        { text: '创建时间', align: 'start', value: 'createdTime', useSlot: true },
        { text: '审核状态', align: 'start', value: 'state', useSlot: true },
        { text: '租户状态', align: 'start', value: 'disable', useSlot: true },
        { text: '操作', align: 'start', value: 'actions', useSlot: true }
      ],
      items: [],
      total: 0,
      pageInfo: {
        size: 10,
        current: 1
      },
      loading: true,
      visible: false,
      rolesLoading: false,
      selected: [],
      id: null,
      visibleExamine: false,
      formOption: {
        options: [
          {
            type: 'ifRadio',
            key: 'state',
            value: '1',
            label: '公司状态',
            items: [{ label: '有效', value: '1' }, { label: '拒绝', value: '2' }],
            change: this.handleChangeState
          },
          {
            type: 'textarea',
            key: 'message',
            hide: true,
            value: '',
            label: '拒绝原因'
          }
        ]
      },
      visibleDetails: false,
      desserts: [],
      diction: [],
      roles: []
    }
  },
  async created () {
    this.initPage()
  },
  methods: {
    // 获取所有菜单
    async getMenu () {
      if (this.roles.length) return
      try {
        const { data } = await getRouters({})
        this.roles = data
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    // findItemById (id) {
    //   // 根据节点的 id 查找节点
    //   let nodes = cloneDeep(this.roles)
    //   while (nodes.length > 0) {
    //     const currentNode = nodes.shift()
    //     if (currentNode.id === id) {
    //       return currentNode
    //     }
    //     if (currentNode.children && currentNode.children.length) {
    //       nodes = nodes.concat(currentNode.children)
    //     }
    //   }
    //   return null
    // },
    // findParentNodes (node) {
    //   // 递归获取节点的所有父节点
    //   const parents = []
    //   let parent = this.findItemById(node.parentId)
    //   while (parent) {
    //     parents.push(parent)
    //     parent = this.findItemById(parent.parentId)
    //   }
    //   return parents
    // },
    async initPage () {
      this.loading = true
      try {
        const { data } = await getCompanyInfoPage({ ...this.pageInfo })
        this.items = data.records
        this.total = data.total
      } catch (error) {
        this.$snackbar.error(error)
      } finally {
        this.loading = false
      }
    },
    async initDict () {
      try {
        const { data } = await getUserList({ size: 99999999 })
        this.diction = data.records
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    // 审核
    handleExamine (id, state) {
      this.formOption.options.find(e => e.key === 'state').value = state ? state.toString() : '1'
      this.id = id
      this.visibleExamine = true
    },
    // 拒绝启用不生效
    handleReject (state, companyId) {
      const disable = state === 'yes' ? 'no' : 'yes'
      this.$confirm('提示', `是否${disable === 'yes' ? '冻结' : '启用'}该租户`)
        .then(async res => {
          try {
            await companyStateChange({ companyId, disable })
            this.$snackbar.success('修改成功')
            this.initPage()
          } catch (error) {
            this.$snackbar.error(error)
          }
        })
    },
    // 编辑权限
    async handleEditRoles (item) {
      this.selected = []
      await this.getMenu()
      const { companyCode } = item
      this.id = companyCode
      this.visible = true
      this.rolesLoading = true
      try {
        const { data } = await getCompanyDetails({ companyCode })
        if (!data?.menuIds || !data.menuIds.length) return
        // 获取当前权限列表
        this.selected = data.menuIds
      } catch (error) {
        this.$snackbar.error(error)
      } finally {
        this.rolesLoading = false
      }
    },
    // 查看详情
    handleDetails (item) {
      const dict = {
        id: '公司ID',
        name: '公司名称',
        enName: '英文名称',
        creditCode: '统一信用编码',
        industry: '所属行业',
        email: '公司邮箱',
        companyCode: '公司编码',
        phone: '手机号码',
        address: '详细地址',
        homeUserId: '申请人ID',
        hostName: '主机名称',
        // path: '路径',
        state: '审核状态',
        disable: '租户状态',
        createdTime: '创建时间'
      }
      this.visibleDetails = true
      this.desserts = Object.keys(dict).map(key => {
        let value = item[key]
        if (key === 'disable') {
          value = value === 'no' ? '已启用' : '已冻结'
        }
        if (key === 'state') {
          value = this.state[value].label
        }
        if (key === 'createdTime') {
          value = this.dateFormat(value)
        }
        return { key: dict[key], value }
      })
    },
    handleChangeState (val) {
      const _this = this.formOption.options.find(e => e.key === 'message')
      if (val === '2') {
        _this.hide = false
        return
      }
      _this.hide = true
    },
    async handleSaveExamine () {
      const state = this.formOption.options.find(e => e.key === 'state').value
      const message = state === '1' ? '' : this.formOption.options.find(e => e.key === 'message').value
      const obj = {
        companyId: this.id,
        state,
        roleId: 'company_admin',
        message: {
          message,
          tag: ''
        }
      }
      try {
        await companyOperateState(obj)
        this.$snackbar.success('审核完成')
        this.visibleExamine = false
        this.id = null
        this.initPage()
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    // 租户套餐保存
    async handleSave () {
      // 获取所有父节点
      try {
        await saveCompanyPackage({
          companyCode: this.id,
          menuIds: this.selected
        })
        this.$snackbar.success('编辑成功')
        await this.$store.dispatch('menu/getMenu2')
        this.id = null
        this.visible = false
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    pageHandleChange (page) {
      this.pageInfo.current = page
      this.initPage()
    },
    dateFormat (str) {
      const date = new Date(+str * 1000)
      return dateFormat('YYYY-mm-dd HH:MM:SS', date)
    }
  }
}
</script>
