import SaveForm from '@/components/save-form'
import Pagination from '@/components/pagination'
import {DataTableRowKey, NButton, NDataTable, NFormItem, NInput, NModal, NSelect, NSpace, NTag, useDialog, useMessage} from 'naive-ui'
import {defineComponent, onMounted, reactive, ref} from 'vue'
import {rollCallSettingPage, rollCallSettingRemove, rollCallSettingStatus} from "@views/music-library/api";
import Edit from "@views/music-library/calligraphy/modal/edit";

export default defineComponent({
  name: 'music-calligraphy',
  setup(props, {emit}) {
    const dialog = useDialog()
    const message = useMessage()
    const state = reactive({
      loading: false,
      pagination: {
        page: 1,
        rows: 10,
        pageTotal: 0
      },
      searchForm: {
        keyword: null,
        status: null,
      },
      showEdit: false,
      editMode: 'add' as any,
      dataList: [] as any,
      rowData: null as any,

    })

    const columns = (): any => {
      return [
        {
          type: 'selection'
        },
        {
          title: '编号',
          key: 'id',
        },
        {
          title: '调号',
          key: 'name',
        },
        {
          title: '连接地址',
          key: 'url',
        },
        {
          title: '更新人',
          key: 'updateName',
        },
        {
          title: '更新时间',
          key: 'updateTime',
        },
        {
          title: '消息状态',
          key: 'status',
          render(row: any) {
            return (
                <NTag type={row.status ? 'primary' : 'default'}>{row.status ? '启用' : '停用'}</NTag>
            )
          }
        },
        {
          title: '操作',
          key: 'operation',
          fixed: 'right',
          width: '300px',
          render(row: any) {
            return (
                <NSpace>
                  <NButton
                      type="primary"
                      size="small"
                      text
                      // v-auth="musicSheet/save1751241178962984962"
                      onClick={() => {
                        state.showEdit = true
                        state.editMode = 'edit'
                        state.rowData = row
                      }}
                  >
                    修改
                  </NButton>
                  <NButton
                      type="primary"
                      size="small"
                      text
                      // v-auth="musicSheet/statusList1751241653309407234"
                      onClick={() => onChangeStatus(row)}
                  >
                    {row.status ? '停用' : '启用'}
                  </NButton>
                  <NButton
                      type="primary"
                      size="small"
                      text
                      disabled={!!row.status}
                      onClick={() => onRmove(row)}
                      // v-auth="musicSheet/remove1753457445635645442"
                  >
                    删除
                  </NButton>
                </NSpace>
            )
          }
        }
      ]
    }

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

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

    const onBatchChangeStatus = (status: boolean) => {
      const length = checkedRowKeysRef.value.length
      if (length == 0) {
        message.warning('未选择数据')
      }
      const statusStr = !status ? '停用' : '启用'
      dialog.warning({
        title: '提示',
        content: `是否${statusStr}` + length + `条数据？`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          try {
            await rollCallSettingStatus({
              ids: checkedRowKeysRef.value,
              status: status
            })
            getList()
            message.success(`${statusStr}成功`)
          } catch {
          }
        }
      })
    }

    const onRmove = (row: any): void => {
      dialog.warning({
        title: '提示',
        content: `删除"${row.name}"，是否继续？`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          try {
            await rollCallSettingRemove(row.id)
            getList()
            message.success('删除成功')
          } catch {
          }
        }
      })
    }

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

    const saveForm = ref()
    const onSubmit = () => {
      state.pagination.page = 1
      getList()
    }
    const onSearch = () => {
      saveForm.value?.submit()
    }
    const onBtnReset = () => {
      saveForm.value?.reset()
    }

    onMounted(async () => {
      state.loading = true
      // getTagList()
      getList()
    })

    return () => (
        <div class="system-menu-container">
          <SaveForm
              ref={saveForm}
              model={state.searchForm}
              onSubmit={onSubmit}
              saveKey="music-calligraphy"
              onSetModel={(val: any) => (state.searchForm = val)}
          >
            <NFormItem label="关键词" path="keyword">
              <NInput
                  placeholder="请输入编号/调号"
                  v-model:value={state.searchForm.keyword}
                  clearable
              />
            </NFormItem>
            <NFormItem label="状态" path="status">
              <NSelect
                  placeholder="请选择多声轨渲染"
                  v-model:value={state.searchForm.status}
                  options={[
                    {
                      label: '是',
                      value: true
                    },
                    {
                      label: '否',
                      value: false
                    }
                  ] 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']}>
            <NSpace style={{paddingBottom: '12px'}}>
              <NButton
                  type="primary"
                  // v-auth="musicSheet/save1751241178962984962"
                  onClick={() => {
                    state.showEdit = true
                    state.editMode = 'add'
                  }}
              >
                新增
              </NButton>
              <NButton
                  disabled={checkedRowKeysRef.value.length == 0}
                  // v-auth="musicSheet/statusList1751241653309407234"
                  onClick={() => {
                    onBatchChangeStatus(false)
                  }}
              >
                批量停用
              </NButton>
              <NButton
                  disabled={checkedRowKeysRef.value.length == 0}
                  // v-auth="musicSheet/statusList1751241653309407234"
                  onClick={() => {
                    onBatchChangeStatus(true)
                  }}
              >
                批量启用
              </NButton>
            </NSpace>

            <NDataTable
                loading={state.loading}
                columns={columns()}
                data={state.dataList}
                rowKey={(row: any) => row.id}
                onUpdateCheckedRowKeys={handleCheck}
                scrollX={'1200'}
            ></NDataTable>
            <Pagination
                v-model:page={state.pagination.page}
                v-model:pageSize={state.pagination.rows}
                v-model:pageTotal={state.pagination.pageTotal}
                onList={getList}
                sync
                saveKey="music-list"
            ></Pagination>
          </div>

          <NModal
              blockScroll={true}
              v-model:show={state.showEdit}
              preset="dialog"
              showIcon={false}
              title={state.editMode == 'add' ? '新增' : '修改'}
              style={{width: '500px'}}
          >
            <Edit
                rowData={state.rowData}
                editMode={state.editMode}
                onClose={() => (state.showEdit = false)}
                onGetList={getList}
            />
          </NModal>
        </div>
    )
  }
})
