import {NButton, NDataTable, NFormItem, NInput, NSelect, NSpace, useDialog, useMessage} from 'naive-ui'
import {defineComponent, onMounted, PropType, reactive, ref} from 'vue'
import {musicSheetApplicationOwnerList} from '../../api'
import SaveForm from "@components/save-form";
import Pagination from "@components/pagination";
import {clientType} from "@/utils/constant";
import {getMapValueByKey} from "@/utils/objectUtil";
import deepClone from "@/utils/deep.clone";

export default defineComponent({
  name: 'musicSheetOwnerDialog',
  props: {
    musicSheetExtend: {
      type: Object as PropType<any>,
      default: () => {
      }
    },
    sourceType: {
      type: String,
      required: true
    },
    appData: {
      type: Array,
      required: true,
      default: []
    }

  },
  emits: ['close', 'getList', "choseMusicSheetOwnerData"],
  setup(props, {slots, attrs, emit}) {
    const state = reactive({
      loading: false,
      pagination: {
        page: 1,
        rows: 10,
        pageTotal: 0
      },
      searchForm: {
        applicationId: null,
        name: null,
        sourceType: null as any,
      },
      dataList: [],
      appData: [] as any, // 适用项目行数据
    })

    const message = useMessage()
    const saveForm = ref()

    const onSubmit = () => {
      state.pagination.page = 1
      getList()
    }
    const onSearch = () => {
      saveForm.value?.submit()
    }
    const getList = async () => {
      try {
        const applicationId = state.searchForm.applicationId;
        if (!applicationId) {
          message.warning("获取应用列表失败");
        }
        state.loading = true
        state.searchForm.sourceType = props.sourceType
        const {data} = await musicSheetApplicationOwnerList({...state.pagination, ...state.searchForm})
        state.pagination.pageTotal = Number(data.total)
        state.dataList = data.rows || []
      } catch {
      }
      state.loading = false
    }

    onMounted(async () => {
      // 初始化应用
      {
        // const appKeys = Object.keys(appKey);
        //
        // const {data} = await sysApplicationPage({page: 1, rows: 999, parentId: 0})
        // const tempList = data.rows || []
        // const filter = tempList.filter((next: any) => {
        //   return appKeys.includes(next.appKey)
        // });
        // filter.forEach((item: any) => {
        //   item.label = item.appName
        //   item.value = item.id
        // })
        state.appData = deepClone(props.appData)
        if (state.appData.length == 0) {
          message.warning("获取应用列表失败")
          return
        }

        if (props.musicSheetExtend && props.musicSheetExtend.applicationId) {
          state.searchForm.applicationId = props.musicSheetExtend.applicationId
        } else {
          state.searchForm.applicationId = state.appData[0].value
        }
        state.searchForm.name = null
      }

      getList()
    })
    const columns = (): any => {
      if (state.searchForm.sourceType === 'ORG') {
        return [
          {
            title: '机构名称',
            key: 'orgName'
          },
          {
            title: '操作',
            key: 'operation',
            fixed: 'right',
            render(row: any) {
              return (
                  <NSpace>
                    <NButton
                        type="primary"
                        size="small"
                        text
                        onClick={() => {
                          const choseMusicSheetOwnerData = {
                            ...row,
                            applicationId: state.searchForm.applicationId
                          }
                          emit("choseMusicSheetOwnerData", choseMusicSheetOwnerData)
                          emit('close')
                        }}
                    >
                      选择
                    </NButton>
                  </NSpace>
              )
            }
          }
        ]
      } else {
        return [
          {
            title: '人员名称',
            key: 'userName'
          },
          {
            title: '手机号',
            key: 'phone'
          },
          {
            title: '操作',
            key: 'operation',
            fixed: 'right',
            render(row: any) {
              return (
                  <NSpace>
                    <NButton
                        type="primary"
                        size="small"
                        text
                        onClick={() => {
                          const choseMusicSheetOwnerData = {
                            ...row,
                            applicationId: state.searchForm.applicationId
                          }
                          emit("choseMusicSheetOwnerData", choseMusicSheetOwnerData)
                          emit('close')
                        }}
                    >
                      选择
                    </NButton>
                  </NSpace>
              )
            }
          }
        ]
      }
    }

    const orgColumns = (): any => {
      return [
        {
          title: '机构名称',
          key: 'organizationRole'
        },
        {
          title: '操作',
          key: 'operation',
          fixed: 'right',
          render(row: any) {
            return (
                <NSpace>
                  <NButton
                      type="primary"
                      size="small"
                      text
                      onClick={() => {
                        const choseMusicSheetOwnerData = {
                          ...row,
                          applicationId: state.searchForm.applicationId
                        }
                        emit("choseMusicSheetOwnerData", choseMusicSheetOwnerData)
                        emit('close')
                      }}
                  >
                    选择
                  </NButton>
                </NSpace>
            )
          }
        }
      ]
    }


    return () => (
        <div class="system-menu-container">
          <SaveForm
              ref={saveForm}
              model={state.searchForm}
              onSubmit={onSubmit}
              // saveKey="musicSheetOwnerDialog"
              onSetModel={(val: any) => (state.searchForm = val)}
          >
            <NFormItem label="所属项目" path="applicationId" size="small" style={'width:250px'}>
              <NSelect
                  placeholder="请选择适用所属项目"
                  v-model:value={state.searchForm.applicationId}
                  options={state.appData}
              />
            </NFormItem>
            {state.searchForm.sourceType === 'PERSON' &&
                (<>
                  <NFormItem label="所属人" path="name" size="small" style={'width:250px'}>
                    <NInput
                        placeholder="请输入所属人/手机号"
                        v-model:value={state.searchForm.name}
                        clearable
                    />
                  </NFormItem>
                </>)}

            {state.searchForm.sourceType === 'ORG' &&
                (<>
                  <NFormItem label="机构名称" path="name" size="small" style={'width:250px'}>
                    <NInput
                        placeholder="请输入机构名称"
                        v-model:value={state.searchForm.name}
                        clearable
                    />
                  </NFormItem>
                </>)}
            <NFormItem size="small">
              <NSpace>
                <NButton type="primary" onClick={onSearch}>
                  搜索
                </NButton>
              </NSpace>
            </NFormItem>
          </SaveForm>
          <div class={['section-container']}>
            {props.sourceType === 'PERSON' &&
                (<NDataTable
                    loading={state.loading}
                    columns={columns()}
                    data={state.dataList}
                ></NDataTable>)}
            {props.sourceType === 'ORG' &&
                (<NDataTable
                    loading={state.loading}
                    columns={orgColumns()}
                    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="musicSheetOwnerDialog"
                pageSlot={5}
            ></Pagination>
          </div>
        </div>
    )
  }
})
