<template>
  <div class="default-main" >
    <el-row :gutter="20">
      <el-col :span="4" :lg="4" :xl="4" :md="24" :xs="24" :sm="24">
        <el-card class="el-card is-hover-shadow" header="企业架构">
          <el-row>
            <el-col :span="24">
              <el-tree :data="treeUtils.treeObj.data" :props="treeUtils.defaultProps" @current-change="name"
                style="color: rgba(0, 0, 0, 0.65)" :default-expand-all="true" ref="tree" node-key="id" />
            </el-col>
          </el-row>
        </el-card>
      </el-col>
      <el-col :span="20" :lg="20" :xl="20" :md="24" :xs="24" :sm="24">
        <el-card class="el-card is-hover-shadow" header="员工列表">
          <!-- style="height:calc(100vh - 107px);"-->
          <el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info"
            show-icon />

          <el-row>
            <el-col :span="24">
              <!-- 表格顶部菜单 -->
              <TableHeader :buttons="['refresh', 'add', 'edit', 'delete', 'comSearch']"
                quick-search-placeholder="通过员工姓名模糊搜索" @action="baTable.onTableHeaderAction" />

              <Table @action="baTable.onTableAction" />
            </el-col>

            <!-- 表单 -->
            <PopupForm ref="formRef" />

            <!-- 表单 -->
            <InfoDialog />
          </el-row>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { provide, ref, reactive, toRefs, onMounted, watch } from 'vue'
import baTableClass from '/@/utils/baTable'
import Table from '/@/components/table/index.vue'
import TableHeader from '/@/components/table/header/index.vue'
import PopupForm from './popupForm.vue'
import { enterpriseEmployee, sysOrg} from '/@/api/controllerUrls'
import { info } from '/@/api/backend/enterprise/employee'
import InfoDialog from './info.vue'
import useCurrentInstance from '/@/utils/useCurrentInstance'
import { defaultOptButtons } from '/@/components/table'
import { baTableApi } from '/@/api/common'

import { ElForm } from 'element-plus'
import treeClass from '/@/utils/tree'

const tableRef = ref()

const tree = ref()

let optButtons: OptButton[] = [
    {
        render: 'tipButton',
        name: 'info',
        title: 'info',
        text: '',
        type: 'primary',
        icon: 'fa fa-search-plus',
        class: 'table-row-info',
        disabledTip: false,
    },
]
optButtons = optButtons.concat(defaultOptButtons(['edit', 'delete']))

const baTable = new baTableClass(
    new baTableApi(enterpriseEmployee),
    {
        column: [
            { type: 'selection', align: 'center', operator: false },
            { label: '姓名', prop: 'trueName', align: 'center', operator: false, fixed: 'left' },
            { label: '照片', prop: 'previewPicture', render: 'image', align: 'center', operator: false },
            {
                label: '部门',
                prop: 'departmentName',
                align: 'center',
                operator: false,
            },
            { label: '职务', prop: 'postName', align: 'center', operator: false },
            { label: '性别', prop: 'sexName', align: 'center', operator: false },
            {
                label: '手机',
                prop: 'mobile',
                align: 'center',
                operator: 'LIKE',
                operatorPlaceholder: '模糊查询',
                width: 120,
            },
            { label: '入职日期', prop: 'hireDate', align: 'center', render: 'dateType', sortable: 'custom', operator: 'RANGE', width: 120 },
            { label: '签订日期', prop: 'contractDate', align: 'center', operator: false, width: 120, show: false },
            { label: '有效天数', prop: 'validDays', align: 'center', operator: false, width: 120, show: false },
            {
                label: '平台账号',
                align: 'center',
                render: 'textBoolen',
                prop: 'platformAccount',
                operator: false,
                width: 120,
            },
            {
                label: '企业微信',
                align: 'center',
                render: 'tag',
                prop: 'enterpriseWechatBindStatusName',
                custom: {'已绑定': 'success', '未绑定': ''},
                operator: false,
                width: 120,
            },
            { label: '修改时间', prop: 'updateTime', render: 'datetime', sortable: 'custom', align: 'center', operator: false, width: 180 },
            {
                label: '操作',
                align: 'center',
                width: '180',
                render: 'buttons',
                buttons: optButtons,
                operator: false,
                fixed: 'right',
            },
        ],
        dblClickNotEditColumn: [undefined, 'status'],
    },
    {
        defaultItems: {
            departmentName: '',
            departmentPids: '',
            departmentId: '',
            sex: '0',
        },
    },
    {
        // 提交前
        onSubmit: (params: { formEl: InstanceType<typeof ElForm> }) => {
            var items = cloneDeep(baTable.form.items!)

            // 表单验证通过后执行的api请求操作
            let submitCallback = () => {
                baTable.form.submitLoading = true
                baTable.api
                    .postData(baTable.form.operate!, items)
                    .then((res) => {
                        baTable.onTableHeaderAction('refresh', {})
                        baTable.form.submitLoading = false
                        baTable.form.operateIds?.shift()
                        if (baTable.form.operateIds?.length! > 0) {
                            baTable.toggleForm('edit', baTable.form.operateIds)
                        } else {
                            treeUtils.BindTrees()
                            baTable.toggleForm()
                        }
                        baTable.runAfter('onSubmit', { res })
                    })
                    .catch((err) => {
                        baTable.form.submitLoading = false
                    })
            }

            if (params.formEl) {
                baTable.form.ref = params.formEl
                params.formEl.validate((valid) => {
                    if (valid) {
                        submitCallback()
                    }
                })
            } else {
                submitCallback()
            }
            return false
        },
    }
)

const treeUtils = new treeClass(sysOrg + 'initialOrgTree', { children: 'children', label: 'label' })

const infoButtonClick = (data: any) => {
    baTable.form.extend!['info'] = {}
    baTable.form.operate = 'info'
    baTable.form.loading = true
    info(data).then((res) => {
        baTable.form.extend!['info'] = res.data
        baTable.form.loading = false
    })
}

provide('baTable', baTable)

onMounted(() => {
    const { proxy } = useCurrentInstance()
    treeUtils.BindTrees()
    let node = getNode()
    baTable.table.ref = tableRef.value
    baTable.form.defaultItems!.parentName = node ? node.label : '无顶级'
    baTable.form.defaultItems!.departmentId = 0
    baTable.form.defaultItems!.departmentPids = '0'
    baTable.mount()
    baTable.getIndex()

    /**
     * 表格内的按钮响应
     * @param name 按钮name
     * @param row 被操作行数据
     */
    proxy.eventBus.on('onTableButtonClick', (data: { name: string; row: TableRow }) => {
        if (!baTable.activate) return
        if (data.name == 'info') {
            let req = { id: '', pid: '' }
            req.id = data.row[baTable.table.pk!]
            req.pid = baTable.table.filter!.pid
            infoButtonClick(req)
        }
    })
})

function name(treeItem: { pid: number; label: String; id: number }) {
    baTable.form.defaultItems!.parentName = treeItem.label
    baTable.form.defaultItems!.departmentId = treeItem.id
    baTable.form.defaultItems!.departmentPids = treeUtils.FindTreePids(treeItem.pid)
    baTable.table.filter!.pid = treeItem.id
    baTable.onTableHeaderAction('refresh', { loading: true })
}

function getNode() {
    return tree.value.getNode(0)
}

watch(
    () => baTable.table.actionStruct,
    (newVal) => {
        if (newVal?.name == 'del') {
            newVal.data.map((item: number) => {
                tree.value.remove(item)
            })
        }

        if (newVal?.name == 'edit') {
            tree.value.getNode(newVal.data.id).label = newVal.data.label
        }
    },
    { deep: true }
)
</script>

<script lang="ts">
import { defineComponent } from 'vue'
import { cloneDeep, String } from 'lodash'
export default defineComponent({
    name: 'organizational/employee',
})
</script>

<style scoped></style>
