import SaveForm from '@/components/save-form'
import {DataTableColumn, NButton, NDataTable, NDatePicker, NFormItem, NImage, NInput, NModal, NSelect, NSpace, NTag, 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";
import axios from "axios";
import cleanDeep from "clean-deep";

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: null,
      times: null as any,
      operatorKeyword: null, //创建人
      categoryId: null,//声部分类
      musicalInstrumentId: null,//关联乐器
    })

    const columns = (): DataTableColumn[] => {
      return [
        {
          title: '编号',
          key: 'id'
        },
        {
          title: '声部名称',
          key: 'name',
        },
        {
          title: '声部分类',
          key: 'categoryName'
        },
        {
          title: '声部编码',
          key: 'code'
        },
        {
          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: 'enableFlag',
          render(row: any) {
            return (
                <NTag type={row.enableFlag ? 'primary' : 'default'}>{row.enableFlag ? '启用' : '停用'}</NTag>
            )
          }
        },
        {
          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 {
            const res = await subjectUpdateStatus({
              id: row.id
            }) as any
            if (res.code == '999') {
              dialog.warning({
                title: '提示',
                content: res.message,
                type: 'warning',
                positiveText: '确定',
                negativeText: '取消',
                onPositiveClick: async () => {
                  await subjectUpdateStatus({
                    id: row.id,
                    confirm: true
                  })
                }
              })
            }
            getList()
            message.success(`${statusStr}成功`)
          } catch {
          }
        }
      })
    }

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

    return () => (
        <div class="system-menu-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:value={searchForm.categoryId}
                  filterable
                  options={state.categorizeList}
                  clearable
              />
            </NFormItem>
            <NFormItem path="musicalInstrumentId" label="关联乐器">
              <NSelect
                  v-model:value={searchForm.musicalInstrumentId}
                  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>
          <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>
    )
  }
})
