import { defineComponent, onMounted, reactive, ref } from 'vue'
import SaveForm from '@components/save-form'
import {
  DataTableRowKey,
  NButton,
  NDataTable,
  NFormItem,
  NInput,
  NModal,
  NSelect,
  NSpace,
  NTag,
  useDialog,
  useMessage
} from 'naive-ui'
import Pagination from '@components/pagination'
import TheTooltip from '@components/TheTooltip'
import { getMapValueByKey, getSelectDataFromObj } from '@/utils/objectUtil'
import { clientType, messageSenderFunctionModule, messageSenderMode } from '@/utils/constant'
import { sysMessageConfigPage, sysMessageConfigStatus } from '@views/message/api'
import deepClone from '@/utils/deep.clone'
import MessageTemplateEdit from '@views/message/message-template/modal/message-template-edit'

export default defineComponent({
  name: 'message-template-list',
  props: {
    appKey: {
      type: String,
      default: 'kT'
    }
  },

  setup(props) {
    const dialog = useDialog()
    const message = useMessage()
    const state = reactive({
      loading: false,
      appId: null as any,
      pagination: {
        page: 1,
        rows: 10,
        pageTotal: 0
      },
      searchForm: {
        description: null, //消息名称
        sendMode: null, // 消息类型
        clientId: null, //客户端
        model: null,
        sendFlag: null
      },
      dataList: [] as any[],
      showEdit: false,
      editMode: 'add',
      editRowData: {} as any
    })

    onMounted(async () => {
      // 加载表格数据
      getList()
    })

    const saveForm = ref()

    const onSearch = () => {
      saveForm.value?.submit()
    }
    const onBtnReset = () => {
      saveForm.value?.reset()
    }

    const onSubmit = () => {
      state.pagination.page = 1
      getList()
    }

    const checkedRowKeysRef = ref<DataTableRowKey[]>([])
    const handleCheck = (rowKeys: DataTableRowKey[]) => {
      checkedRowKeysRef.value = rowKeys
    }

    const getList = async () => {
      try {
        state.loading = true
        const { data } = await sysMessageConfigPage({
          ...state.pagination,
          ...state.searchForm,
          appKey: props.appKey
        })
        state.pagination.pageTotal = Number(data.total)
        state.dataList = data.rows || []
      } catch {}
      state.loading = false
    }

    const onChangeStatus = (row: any) => {
      const statusStr = row.sendFlag ? '停用' : '启用'
      dialog.warning({
        title: '提示',
        content: `是否${statusStr}？`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          try {
            await sysMessageConfigStatus({
              id: row.id,
              sendFlag: row.sendFlag == 1 ? 0 : 1
            })
            getList()
            message.success(`${statusStr}成功`)
          } catch {}
        }
      })
    }

    const columns = (): any => {
      return [
        {
          title: '编号',
          key: 'id'
        },
        {
          title: '消息名称',
          key: 'description'
        },
        {
          title: '消息发送类型',
          key: 'sendMode',
          render: (row: any) => {
            return (
              <div>
                {getMapValueByKey(row.sendMode, new Map(Object.entries(messageSenderMode)))}
              </div>
            )
          }
        },
        {
          title: '客户端',
          key: 'clientId',
          render: (row: any) => {
            return <div>{getMapValueByKey(row.clientId, new Map(Object.entries(clientType)))}</div>
          }
        },
        {
          title: '消息类型',
          key: 'messageType'
        },
        {
          title: '功能模块',
          key: 'group',
          render: (row: any) => {
            return (
              <div>
                {getMapValueByKey(row.group, new Map(Object.entries(messageSenderFunctionModule)))}
              </div>
            )
          }
        },
        {
          title: '触发条件',
          key: 'triggerCondition'
        },
        {
          title: '参数',
          key: 'params'
        },
        {
          title: '消息模板',
          key: 'content',
          minWidth: '200px',
          render(row: any) {
            return <TheTooltip showContentWidth={300} content={row.content} />
          }
        },
        {
          title: '示例',
          key: 'contentExample',
          render(row: any) {
            return <TheTooltip showContentWidth={300} content={row.contentExample} />
          }
        },
        {
          title: '更新人',
          key: 'operatorName'
        },
        {
          title: '更新时间',
          key: 'updateTime'
        },
        {
          title: '状态',
          key: 'sendFlag',
          render(row: any) {
            return (
              <NTag type={row.sendFlag ? 'primary' : 'default'}>
                {row.sendFlag ? '启用' : '停用'}
              </NTag>
            )
          }
        },
        {
          title: '操作',
          key: 'operation',
          fixed: 'right',
          render(row: any) {
            return (
              <NSpace>
                <NButton
                  type="primary"
                  size="small"
                  text
                  v-auth="sysMessageConfig/status1790940236048568322"
                  onClick={() => onChangeStatus(row)}
                >
                  {row.sendFlag ? '停用' : '启用'}
                </NButton>
                {/*<NButton*/}
                {/*    type="primary"*/}
                {/*    size="small"*/}
                {/*    text*/}
                {/*    onClick={() => {*/}
                {/*      state.showEdit = true*/}
                {/*      state.editRowData = deepClone(row)*/}
                {/*      state.editMode = 'edit'*/}
                {/*    }}*/}
                {/*>*/}
                {/*  修改*/}
                {/*</NButton>*/}
              </NSpace>
            )
          }
        }
      ]
    }

    return () => {
      return (
        <div class="system-menu-container">
          <SaveForm
            ref={saveForm}
            model={state.searchForm}
            onSubmit={onSubmit}
            saveKey="message-template"
            onSetModel={(val: any) => (state.searchForm = val)}
          >
            <NFormItem label="消息名称" path="description">
              <NInput
                placeholder="请输入消息名称"
                v-model:value={state.searchForm.description}
                clearable
              />
            </NFormItem>
            <NFormItem label="消息类型" path="sendMode">
              <NSelect
                placeholder="全部类型"
                v-model:value={state.searchForm.sendMode}
                options={getSelectDataFromObj(messageSenderMode)}
                clearable
              />
            </NFormItem>
            <NFormItem label="客户端" path="clientId">
              <NSelect
                placeholder="请选择所属项目"
                v-model:value={state.searchForm.clientId}
                options={getSelectDataFromObj(clientType)}
                clearable
              />
            </NFormItem>
            <NFormItem label="功能模块" path="model">
              <NSelect
                filterable
                placeholder="全部功能模块"
                options={getSelectDataFromObj(messageSenderFunctionModule)}
                clearable
              ></NSelect>
            </NFormItem>
            <NFormItem label="状态" path="status">
              <NSelect
                v-model:value={state.searchForm.sendFlag}
                placeholder="请选择状态"
                options={
                  [
                    {
                      label: '启用',
                      value: 1
                    },
                    {
                      label: '停用',
                      value: 0
                    }
                  ] as any
                }
                clearable
              />
            </NFormItem>
            <NFormItem>
              <NSpace>
                <NButton type="primary" onClick={onSearch}>
                  搜索
                </NButton>
                <NButton type="default" onClick={onBtnReset}>
                  重置
                </NButton>
              </NSpace>
            </NFormItem>
          </SaveForm>

          <div class={['section-container']}>
            <NDataTable
              loading={state.loading}
              columns={columns()}
              data={state.dataList}
              rowKey={(row: any) => row.applicationExtendId}
              // onUpdateCheckedRowKeys={handleCheck}
              scrollX={'1400'}
            ></NDataTable>

            <Pagination
              v-model:page={state.pagination.page}
              v-model:pageSize={state.pagination.rows}
              v-model:pageTotal={state.pagination.pageTotal}
              onList={getList}
              sync
              saveKey="message-template"
            ></Pagination>
          </div>
          <NModal
            blockScroll={true}
            v-model:show={state.showEdit}
            preset="dialog"
            showIcon={false}
            title={(state.editMode == 'add' ? '新增' : '编辑') + '消息模板'}
            // style={{width: 'auto'}}
            style={{ width: '700px' }}
          >
            <MessageTemplateEdit
              editMode={state.editMode}
              rowData={state.editRowData}
              onClose={() => (state.showEdit = false)}
              onGetList={() => {
                state.pagination.page = 1
                getList()
              }}
            />
          </NModal>
        </div>
      )
    }
  }
})
