import Pagination from '@/components/pagination'
import {
  NButton,
  NDataTable,
  NDatePicker,
  NFormItem,
  NInput,
  NModal,
  NSelect,
  NSpace,
  NTag,
  useDialog,
  useMessage
} from 'naive-ui'
import { defineComponent, onMounted, reactive, ref } from 'vue'
import SaveForm from '@components/save-form'
import {
  musicalInstrumentPage,
  musicalInstrumentUpdateStatus
} from '@views/system-manage/subject-manage/api'
import { getMapValueByKey } from '@/utils/filters'
import { defaultScore } from '@/utils/constant'
import { getSelectDataFromObj } from '@/utils/objectUtil'
import InstrumentSave from '@views/system-manage/subject-manage/instrument/modal/instrument-save'
import { filterTimes } from '@/utils/dateUtil'

export default defineComponent({
  name: 'instrument-list',
  setup() {
    const dialog = useDialog()
    const message = useMessage()
    const state = reactive({
      loading: false,
      pagination: {
        page: 1,
        rows: 10,
        pageTotal: 0
      },
      searchForm: {
        keyword: '',
        timer: null,
        startTime: null,
        endTime: null,
        defaultScore: null, //默认谱面
        code: null, //编码
        operatorKeyword: null //操作人
      },
      dataList: [] as any,
      showSave: false,
      saveMode: 'add',
      rowData: {}
    })

    const saveForm = ref()

    const onSubmit = () => {
      state.pagination.page = 1
      getList()
    }
    const onSearch = () => {
      saveForm.value?.submit()
    }
    const onChangeStatus = (row: any) => {
      const statusStr = row.enableFlag ? '停用' : '启用'
      dialog.warning({
        title: '提示',
        content: `是否${statusStr}？`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          try {
            await musicalInstrumentUpdateStatus({
              id: row.id
            })
            getList()
            message.success(`${statusStr}成功`)
          } catch {}
        }
      })
    }
    const onBtnReset = () => {
      saveForm.value?.reset()
    }

    const columns = () => {
      return [
        {
          title: '编号',
          key: 'id'
        },
        {
          title: '乐器名称',
          key: 'name'
        },
        {
          title: '乐器编码',
          key: 'code'
        },
        {
          title: '声部',
          key: 'subjectName'
        },
        {
          title: '默认谱面',
          key: 'defaultScore',
          render(row: any) {
            return getMapValueByKey(row.defaultScore, new Map(Object.entries(defaultScore)))
          }
        },
        {
          title: '操作人',
          key: 'operator',
          render(row: any) {
            return (
              <div>
                <div>{row.operatorName}</div>
                <div>{row.updateTime}</div>
              </div>
            )
          }
        },
        {
          title: '状态',
          key: 'enableFlag',
          render(row: any) {
            return (
              <NTag type={row.enableFlag ? 'primary' : 'default'}>
                {row.enableFlag ? '启用' : '停用'}
              </NTag>
            )
          }
        },
        {
          title: '操作',
          key: 'operation',
          render(row: any) {
            return (
              <NSpace>
                <NButton
                  type="primary"
                  size="small"
                  text
                  v-auth="musicalInstrument/update1750840718913437697"
                  onClick={() => {
                    state.rowData = row
                    state.showSave = true
                    state.saveMode = 'edit'
                  }}
                >
                  修改
                </NButton>
                <NButton
                  type="primary"
                  size="small"
                  text
                  v-auth="musicalInstrument/enable1750840534934487042"
                  onClick={() => onChangeStatus(row)}
                >
                  {row.enableFlag ? '停用' : '启用'}
                </NButton>
              </NSpace>
            )
          }
        }
      ]
    }

    const getList = async () => {
      try {
        state.loading = true
        const { data } = await musicalInstrumentPage({
          ...state.pagination,
          ...state.searchForm,
          ...filterTimes(state.searchForm.timer, ['startTime', 'endTime'])
        })
        state.loading = false
        state.pagination.pageTotal = Number(data.total)
        state.dataList = data.rows || []
      } catch {
        state.loading = false
      }
    }

    onMounted(() => {
      getList()
    })
    return () => (
      <div class="system-menu-container">
        <div class={['section-container']}>
          <SaveForm
            ref={saveForm}
            model={state.searchForm}
            onSubmit={onSubmit}
            onSetModel={(val: any) => Object.assign(state.searchForm, val)}
            saveKey="instrument-list"
          >
            <NFormItem path="keyword" label="关键字">
              <NInput
                placeholder="请输入编号/名称"
                v-model:value={state.searchForm.keyword}
                clearable
              />
            </NFormItem>
            <NFormItem path="defaultScore" label="默认谱面">
              <NSelect
                options={getSelectDataFromObj(defaultScore)}
                v-model:value={state.searchForm.defaultScore}
                placeholder="请选择默认谱面"
                clearable
              />
            </NFormItem>
            <NFormItem path="code" label="乐器编码">
              <NInput
                v-model:value={state.searchForm.code}
                placeholder="请输入乐器编码"
                clearable
              />
            </NFormItem>
            <NFormItem path="operatorName" label="操作人">
              <NInput
                v-model:value={state.searchForm.operatorKeyword}
                placeholder="请输入操作人"
                clearable
              />
            </NFormItem>
            <NFormItem path="updateTime" label="操作时间">
              <NDatePicker v-model:value={state.searchForm.timer} type="daterange" clearable />
            </NFormItem>

            <NFormItem>
              <NSpace>
                <NButton type="primary" onClick={onSearch}>
                  搜索
                </NButton>
                <NButton type="default" onClick={onBtnReset}>
                  重置
                </NButton>
              </NSpace>
            </NFormItem>
          </SaveForm>
          <NSpace style={{ paddingBottom: '12px' }}>
            <NButton
              type="primary"
              v-auth="musicalInstrument/save1750840633332858882"
              onClick={() => {
                state.rowData = {}
                state.showSave = true
                state.saveMode = 'add'
              }}
            >
              添加
            </NButton>
          </NSpace>

          <NDataTable
            loading={state.loading}
            columns={columns()}
            data={state.dataList}
            rowKey={(row: any) => row.id}
          ></NDataTable>
          <Pagination
            v-model:page={state.pagination.page}
            v-model:pageSize={state.pagination.rows}
            v-model:pageTotal={state.pagination.pageTotal}
            onList={getList}
            sync
            saveKey="login-device"
          ></Pagination>
        </div>
        <NModal
          v-model:show={state.showSave}
          preset="dialog"
          showIcon={false}
          title={state.saveMode === 'add' ? '新增乐器' : '修改乐器'}
          style={{ width: '500px' }}
        >
          <InstrumentSave
            type={state.saveMode}
            data={state.rowData}
            onClose={() => (state.showSave = false)}
            onGetList={getList}
          />
        </NModal>
      </div>
    )
  }
})
