import SaveForm from '@/components/save-form'
import {DataTableColumn, NButton, NDataTable, NDatePicker, NFormItem, NImage, NInput, NModal, NSelect, NSpace, useDialog, useMessage} from 'naive-ui'
import {defineComponent, onMounted, reactive, ref} from 'vue'
import styles from '../index.module.less'
import {musicalInstrumentPage, subjectCategoryPage, subjectPage, subjectUpdateStatus} from "@views/system-manage/subject-manage/api";
import {filterTimes} from "@/utils/dateUtil";
import SubjectSave from "@views/system-manage/subject-manage/subject/modal/subject-save";
import Pagination from "@components/pagination";
import deepClone from "@/utils/deep.clone";

export default defineComponent({
  name: 'subject-list',
  setup() {
    const dialog = useDialog()
    const message = useMessage()
    const state = reactive({
      loading: false,
      pagination: {
        page: 1,
        rows: 10,
        pageTotal: 0
      },
      dataList: [] as any,
      saveMode: 'add',
      showSaveDialog: false,
      rowData: {},
      categorizeList: [] as any,
      instrumentList: [] as any,
    })
    const searchForm = reactive({
      keyword: '',
      times: null as any,
      operatorKeyword: '', //创建人
      categoryId: '',//声部分类
      musicalInstrumentId: '',//关联乐器
    })

    const columns = (): DataTableColumn[] => {
      return [
        {
          title: '编号',
          key: 'id'
        },
        {
          title: '声部名称',
          key: 'name',
        },
        {
          title: '声部分类',
          key: 'categoryName'
        },
        {
          title: '图片',
          key: 'img',
          render(row: any) {
            return <NImage width={70} src={row.img}/>
          }
        },
        {
          title: '关联乐器',
          key: 'musicalInstrumentName'
        },
        {
          title: '操作人',
          key: 'operator',
          render(row: any) {
            return (
                <div>
                  <div>{row.operatorName}</div>
                  <div>{row.updateTime}</div>
                </div>
            )
          }
        },
        {
          title: '操作',
          key: 'operation',
          fixed: 'right',
          width: 180,
          render(row: any) {
            return (
                <NSpace>
                  <NButton
                      type="primary"
                      text
                      //v-auth="materialCategory/update1599962354053140482"
                      onClick={() => {
                        state.saveMode = 'edit'
                        state.showSaveDialog = true
                        state.rowData = row
                      }}
                  >
                    修改
                  </NButton>
                  <NButton
                      type="primary"
                      size="small"
                      text
                      //v-auth="sysNotice/status1599959101026455553"
                      onClick={() => onChangeStatus(row)}
                  >
                    {row.enableFlag ? '停用' : '启用'}
                  </NButton>
                </NSpace>
            )
          }
        }
      ]
    }

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

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

    const initCategoryList = async () => {
      try {
        state.loading = true
        const body = {
          page: 1,
          rows: 9999
        }
        const {data} = await subjectCategoryPage(body)
        state.loading = false

        data.rows.forEach((next: any) => {
          state.categorizeList.push({
            label: next.name,
            value: next.id,
            enableFlag: next.enableFlag,
          })
        })
        console.log(state.categorizeList)
      } catch (e) {
        console.log("err", e);
      }
    }
    const initInstrumentList = async () => {
      try {
        state.loading = true
        const body = {
          page: 1,
          rows: 9999
        }
        const {data} = await musicalInstrumentPage(body)
        state.loading = false

        data.rows.forEach((next: any) => {
          state.instrumentList.push({
            label: next.name,
            value: next.id + '',
            enableFlag: next.enableFlag,
          })
        })
      } catch (e) {

      }
    }

    const getList = async () => {
      try {
        state.loading = true
        const {times, ...reset} = searchForm
        const body = {
          ...reset,
          ...filterTimes(times, ['startTime', 'endTime']),
          page: state.pagination.page,
          rows: state.pagination.rows,

        }
        const {data} = await subjectPage(body)
        state.loading = false
        state.pagination.pageTotal = Number(data.total)
        state.dataList = data.rows || []
      } catch {
        state.loading = false
      }
    }

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

    onMounted(() => {
      getList()
      initCategoryList()
      initInstrumentList()
    })

    return () => (
        <div class="system-menu-container">
          <div class={['section-container']}>
            <SaveForm
                ref={saveForm}
                model={searchForm}
                onSubmit={onSubmit}
                onSetModel={(val: any) => Object.assign(searchForm, val)}
                saveKey="subject-list"
            >
              <NFormItem path="keyword" label="关键字">
                <NInput
                    placeholder="请输入编号/名称"
                    v-model:value={searchForm.keyword}
                    clearable
                />
              </NFormItem>
              <NFormItem path="categoryId" label="声部分类">
                <NSelect
                    placeholder="请选择声部分类"
                    v-model={[searchForm.categoryId, 'value']}
                    filterable
                    options={state.categorizeList}
                    clearable
                />
              </NFormItem>
              <NFormItem path="musicalInstrumentId" label="关联乐器">
                <NSelect
                    v-model={[searchForm.musicalInstrumentId, 'value']}
                    placeholder="请选择关联乐器"
                    filterable
                    options={state.instrumentList}
                    clearable
                />
              </NFormItem>
              <NFormItem path="operatorKeyword" label="操作人">
                <NInput
                    placeholder="请输入操作人"
                    v-model:value={searchForm.operatorKeyword}
                    clearable
                />
              </NFormItem>
              <NFormItem path="times" label="操作时间">
                <NDatePicker
                    class={styles.datepicker}
                    value-format="yyyy.MM.dd"
                    v-model:value={searchForm.times}
                    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="materialCategory/save1599962104022290433"
                  onClick={() => {
                    state.saveMode = 'add'
                    state.showSaveDialog = true
                  }}
                  disabled={state.loading}
              >
                添加
              </NButton>
            </NSpace>
            <NDataTable
                scroll-x="1300"
                loading={state.loading}
                columns={columns()}
                data={state.dataList}
                children-key="subMaterialCategoryList"
                default-expand-all={false}
                row-key={(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.showSaveDialog}
              preset="dialog"
              showIcon={false}
              title={state.saveMode === 'add' ? '添加声部' : '修改声部'}
              style={{width: '400px'}}
          >
            <SubjectSave
                type={state.saveMode}
                data={state.rowData}
                categoryList={deepClone(state.categorizeList)}
                instrumentList={deepClone(state.instrumentList)}
                onClose={() => (state.showSaveDialog = false)}
                onGetList={getList}
            />
          </NModal>
        </div>
    )
  }
})
