import SaveForm from '@/components/save-form'
import Pagination from '@/components/pagination'
import {
  DataTableColumn,
  NButton,
  NCascader,
  NDataTable,
  NDatePicker,
  NDescriptions,
  NDescriptionsItem,
  NFormItem,
  NInput,
  NModal,
  NSelect,
  NSpace,
  NTag,
  NTooltip,
  useDialog,
  useMessage
} from 'naive-ui'
import { defineComponent, inject, onMounted, reactive, ref, provide } from 'vue'
import { fetchCategoryList, fetchMaterialList, deleteMaterial, updateMaterailData } from '../api'
import styles from '../index.module.less'
import { InternalRowData } from 'naive-ui/es/data-table/src/interface'
import AddMaterial from '../model/addMaterial'
import { getLessonType, lessonType } from '@/views/knowledge-manage/knowledgeTypeData'
import { filterTimes, getTimes } from '@/utils/dateUtil'
import { useRoute } from 'vue-router'
import { subjectPage } from '@views/system-manage/subject-manage/api'
import TheTooltip from '@/components/TheTooltip'

const classType: { [_: string]: any } = {
  VIDEO: '视频',
  IMG: '图片',
  SONG: '曲目'
}
const classTypeList = Object.keys(classType).map((key: string) => {
  return { label: classType[key], value: key }
})
export default defineComponent({
  name: 'material-list',
  setup(props) {
    const dialog = useDialog()
    const message = useMessage()
    const state = reactive({
      loading: false,
      pagination: {
        page: 1,
        rows: 10,
        pageTotal: 10
      },
      visiableCity: false,
      dataList: [] as any,
      cityType: 'add',
      materail: null,
      isLook: false,
      employeeList: [] as any
    })
    const searchForm = reactive({
      keyword: null as any,
      time: null as any,
      containMusic: null as any,
      courseTypeCode: null,
      materialCategoryId: null,
      type: null
    })
    const route = useRoute()
    // 获取分类列表
    const category = reactive({
      list: [] as any,
      index: -1
    })
    const getCategoryList = async () => {
      try {
        const { data } = await fetchCategoryList({ page: 1 })
        category.list = data?.rows || []
      } catch {}
    }
    // provide('categoryList', category)
    // 声部
    const subjects = reactive({
      list: [] as any
    })
    const getSubjects = async () => {
      try {
        const { data } = await subjectPage({ page: 1, rows: 1000 })
        subjects.list = data?.rows || []
      } catch {}
    }
    provide('subjects', subjects)

    onMounted(() => {
      console.log(route.query, 'route.query')
      if (route.query.id) {
        searchForm.keyword = route.query.id as string
      }
      getCategoryList()
      getSubjects()
    })

    const columns = (): DataTableColumn[] => {
      return [
        {
          title: '素材名称',
          key: 'name',
          render(row: any) {
            return (
              <NDescriptions labelPlacement="left" column={1}>
                <NDescriptionsItem label="素材名称">{row.name}</NDescriptionsItem>
                <NDescriptionsItem label="素材编号">{row.id}</NDescriptionsItem>
                <NDescriptionsItem label="素材分类">
                  <TheTooltip content={row.materialCategoryName} />
                </NDescriptionsItem>
              </NDescriptions>
            )
          }
        },
        {
          title: '素材信息',
          key: 'sn',
          render(row: any) {
            return (
              <NDescriptions labelPlacement="left" column={1}>
                <NDescriptionsItem label="分段编号">{row.sn}</NDescriptionsItem>
                <NDescriptionsItem label="素材类型">
                  {classType[row.type as string]}
                </NDescriptionsItem>
                {/* <NDescriptionsItem label="课程类型">{row.courseTypeName}</NDescriptionsItem> */}
              </NDescriptions>
            )
          }
        },
        {
          title: '课程信息',
          key: 'type',
          render(row: any) {
            return (
              <NDescriptions labelPlacement="left" column={1}>
                <NDescriptionsItem label="课程类型">{row.courseTypeName}</NDescriptionsItem>
                {/* 
                <NDescriptionsItem label="建议时长">
                  {row.adviseStudyTimeSecond ? row.adviseStudyTimeSecond + '秒' : ''}
                </NDescriptionsItem> */}
              </NDescriptions>
            )
          }
        },
        {
          title: '关联曲目',
          key: 'type',
          render(row: any) {
            return (
              <NDescriptions labelPlacement="left" column={1}>
                <NDescriptionsItem label="曲目名称">
                  <TheTooltip content={row.materialRef?.relateMaterialInfo?.name || '--'} />
                </NDescriptionsItem>
                <NDescriptionsItem label="曲目状态">
                  {row.materialRef?.relateMaterialInfo
                    ? row.materialRef?.relateMaterialInfo?.status
                      ? '启用'
                      : '停用'
                    : '--'}
                </NDescriptionsItem>
              </NDescriptions>
            )
          }
        },
        {
          title: '操作信息',
          key: 'createTime',
          render(row: any) {
            return (
              <NDescriptions labelPlacement="left" column={1}>
                <NDescriptionsItem label="上传人">{row.operatorName}</NDescriptionsItem>

                <NDescriptionsItem label="上传时间">
                  {row.createTime ? row.createTime : '--'}
                </NDescriptionsItem>
              </NDescriptions>
            )
          }
        },
        {
          title: '状态',
          key: 'delFlag',
          render(row: InternalRowData) {
            return (
              <>
                <NTag type={row.enableFlag ? 'success' : 'warning'}>
                  {row.enableFlag ? '启用' : '停用'}
                </NTag>
              </>
            )
          }
        },

        {
          title: '操作',
          key: 'operation',
          fixed: 'right',
          width: 160,
          render(row: any) {
            return (
              <NSpace>
                {/* <NButton
                  type={row.enableFlag ? 'error' : 'success'}
                  text
                  v-auth="material/update1599948375910109186"
                  onClick={() => handleChange(row)}
                >
                  {row.enableFlag ? '停用' : '启用'}
                </NButton> */}
                <NButton
                  type="primary"
                  text
                  onClick={() => {
                    state.isLook = true
                    state.materail = row
                    state.visiableCity = true
                  }}
                >
                  查看
                </NButton>
                <NButton
                  type="primary"
                  text
                  v-auth="material/update1599948375910109186"
                  onClick={() => {
                    state.cityType = 'update'
                    state.materail = row
                    state.visiableCity = true
                  }}
                >
                  修改
                </NButton>
                <NButton
                  type="primary"
                  text
                  disabled={row.enableFlag}
                  v-auth="material/remove1599948195949301762"
                  onClick={() => handleDelete(row)}
                >
                  删除
                </NButton>
              </NSpace>
            )
          }
        }
      ]
    }

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

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

    const getList = async () => {
      try {
        state.loading = true
        const { time, ...reset } = searchForm
        const body = {
          ...reset,
          ...filterTimes(time, ['startTime', 'endTime']),
          page: state.pagination.page,
          rows: state.pagination.rows
        }
        const { data } = await fetchMaterialList(body)
        state.loading = false
        state.pagination.pageTotal = Number(data.total)
        const result = data.rows || []
        result.forEach((item: any) => {
          if (item.materialRefs && item.materialRefs.length > 0) {
            item.materialRef = item.materialRefs[0]
          } else {
            item.materialRef = {}
          }
        })

        state.dataList = result || []
      } catch {
        state.loading = false
      }
    }
    // 删除
    const handleDelete = async (row: any) => {
      dialog.warning({
        title: '警告',
        content: '是否确认删除此素材?',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          const res = await deleteMaterial(row.id)
          if (res.data) {
            onSubmit()
            message.success('删除成功')
          }
        }
      })
    }

    // 启用,停用
    const handleChange = (row: any) => {
      dialog.warning({
        title: '提示',
        content: row.enableFlag ? '是否停用此素材?' : '是否启用此素材?',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          const res = await deleteMaterial(row.id)
          if (res.data) {
            await updateMaterailData({ id: row.id, enableFlag: row.enableFlag ? 0 : 1 })
            message.success('修改成功')
            getList()
          }
        }
      })
    }

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

    return () => (
      <>
        <SaveForm
          ref={saveForm}
          label-width=""
          model={searchForm}
          onSubmit={onSubmit}
          onSetModel={(val: any) => Object.assign(searchForm, val)}
          saveKey="material-key"
        >
          <NFormItem label="搜索条件" path="keyword">
            <NInput
              v-model:value={searchForm.keyword}
              onKeydown={(e) => {
                if (e.code === 'Enter') {
                  onSubmit()
                }
              }}
              placeholder={'素材名称/编号'}
              clearable
            />
          </NFormItem>
          <NFormItem label="素材分类" path="materialCategoryId">
            <NCascader
              v-model:value={searchForm.materialCategoryId}
              options={category.list}
              checkStrategy="child"
              childrenField="subMaterialCategoryList"
              expandTrigger="hover"
              valueField="id"
              labelField="name"
              clearable
              filterable
            />
          </NFormItem>
          <NFormItem label="素材类型" path="type">
            <NSelect clearable v-model:value={searchForm.type} options={classTypeList} />
          </NFormItem>
          <NFormItem label="课程类型" path="courseTypeCode">
            <NSelect clearable v-model:value={searchForm.courseTypeCode} options={lessonType} />
          </NFormItem>
          <NFormItem label="关联曲目" path="containMusic">
            <NSelect
              clearable
              v-model:value={searchForm.containMusic}
              options={
                [
                  { label: '关联', value: true },
                  { label: '不关联', value: false }
                ] as any
              }
            />
          </NFormItem>
          <NFormItem label="搜索时间" path="time">
            <NDatePicker
              class={styles.datepicker}
              v-model:value={searchForm.time}
              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="material/save1599948016487616513"
            onClick={() => {
              state.cityType = 'add'
              state.materail = null
              state.visiableCity = true
            }}
          >
            添加素材
          </NButton>
        </NSpace>
        <NDataTable loading={state.loading} columns={columns()} data={state.dataList}></NDataTable>
        <Pagination
          v-model:page={state.pagination.page}
          v-model:pageSize={state.pagination.rows}
          v-model:pageTotal={state.pagination.pageTotal}
          onList={getList}
          sync
          saveKey="material-key"
        ></Pagination>

        <NModal
          v-model:show={state.visiableCity}
          preset="dialog"
          showIcon={false}
          title={state.cityType === 'add' ? '添加素材' : '修改素材'}
          style={{ width: '700px' }}
          onClose={() => {
            state.isLook = false
          }}
        >
          {state.visiableCity && (
            <AddMaterial
              item={state.materail}
              isLook={state.isLook}
              categoryList={category.list}
              onClose={() => {
                state.visiableCity = false
              }}
              onHandleSuccess={() => {
                state.visiableCity = false
                if (!state.materail) {
                  state.pagination.page = 1
                }
                getList()
              }}
            />
          )}
        </NModal>
      </>
    )
  }
})
