<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElTooltip, ElButtonGroup } from 'element-plus'
import { Table } from '@/components/Table'
import {
  getTableListApi,
  delTableListApi,
  saveTableApi,
  updateTableApi
} from '@/api/manage/company'
import { useTable } from '@/hooks/web/useTable'
import { ref, unref } from 'vue'
import { useEmitt } from '@/hooks/event/useEmitt'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { TableSetting } from '@/components/TableSetting'
import { usePageStore } from '@/store/modules/page'
import { set } from 'lodash-es'
import { useStorage } from '@/hooks/web/useStorage'
import { Dialog } from '@/components/Dialog'
import { CompanyData } from '@/api/manage/types'
import Write from './components/Write.vue'
import { useIcon } from '@/hooks/web/useIcon'
import { Icon } from '@/components/Icon'
import { uploadFile } from '@/api/common'

defineOptions({
  name: 'CompanyPage'
})
const DeleteIcon = useIcon({ icon: 'ep:delete' })
const EditIcon = useIcon({ icon: 'ep:edit' })
const id = ref<string>('')
const { getStorage } = useStorage()
const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}
const currentRow = ref<CompanyData>({
  wechatImg: '',
  companyName: ''
})
const wechatImg = ref('')
const formState = ref<string>('add')
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getTableListApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.list,
      total: Number(res.data.totalCount)
    }
  },
  fetchDelApi: async () => {
    const res = await delTableListApi(unref(id))
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, delList, setColumn } = tableMethods

getList()

useEmitt({
  name: 'getList',
  callback: (type: string) => {
    if (type === 'add') {
      currentPage.value = 1
    }
    getList()
  }
})

const { t } = useI18n()
const appStore = usePageStore()
const dialogVisible = ref(false)
// const fileList = ref([])
const crudSchemas: CrudSchema[] = [
  {
    field: 'companyName',
    label: '公司名称',
    minWidth: 100,
    table: {
      hidden: false
    }
  },

  {
    field: 'companyPhone',
    label: '公司电话',
    minWidth: 120,
    table: {
      hidden: false
    },
    search: {
      hidden: true
    },
    form: {}
  },
  {
    field: 'companyEmail',
    label: '公司邮箱',
    minWidth: 120,
    table: {
      hidden: false
    },
    search: {
      hidden: true
    },
    form: {}
  },
  {
    field: 'companyAddress',
    label: '公司地址',
    minWidth: 120,
    table: {
      hidden: false
    },
    search: {
      hidden: true
    },
    form: {
      hidden: false
    }
  },
  {
    field: 'companyBrief',
    label: '公司简介',
    minWidth: 100,
    table: {
      hidden: false
    },
    search: {
      hidden: true
    },
    form: {
      componentProps: {
        type: 'textarea'
      },
      colProps: {
        span: 24
      }
    }
  },
  {
    field: 'name',
    label: '负责人',
    minWidth: 100,
    table: {
      hidden: false
    },
    form: {}
  },
  {
    field: 'phone',
    label: '负责人电话',
    minWidth: 100,
    table: {
      hidden: false
    },
    search: {
      hidden: true
    },
    form: {}
  },
  {
    field: 'wechat',
    label: '微信账号',
    minWidth: 100,
    table: {
      hidden: false
    },
    search: {
      hidden: true
    },
    form: {}
  },
  {
    field: 'isActive',
    label: '是否启用',
    minWidth: 100,
    table: {
      hidden: false
    },
    search: {
      hidden: true
    },
    form: {
      component: 'Switch',
      value: '1',
      componentProps: {
        activeText: '启用',
        inactiveText: '禁用',
        activeValue: '1',
        inactiveValue: '0'
      }
    }
  },
  {
    field: 'wechatImg',
    label: '微信二维码',
    minWidth: 120,
    search: {
      hidden: true
    },
    table: {
      hidden: false
    },
    form: {
      colProps: {
        span: 24
      },
      component: 'Upload',
      componentProps: {
        httpRequest: (data: any) => {
          // uploadFile(formData).then((response) => {
          //   wechatImg.value = response.data.virtualPath
          //   currentRow.value.wechatImg = response.data.virtualPath
          // })
          let file = data.file
          let formData = new FormData()
          formData.append('file', file)
          uploadFile(file.size <= 1024 * 1000 ? formData : file).then((response) => {
            console.log(response)
            let resUrl = ''
            if (file.size <= 1024 * 1000) {
              resUrl = response.data.virtualPath
            } else {
              resUrl = response.url.replace(
                'xn-back.oss-cn-nanjing.aliyuncs.com',
                'oss.dacundianzi.com'
              )
            }
            wechatImg.value = resUrl
            currentRow.value.wechatImg = resUrl
            const write = unref(writeRef)
            write?.setValues({
              bannerUrl: resUrl
            })
            delLoading.value = false
          })
        },
        limit: 1,
        showFileList: false,
        class: 'companyUploader',
        fileList: wechatImg.value
          ? [
              {
                url: wechatImg.value
              }
            ]
          : [],
        headers: {
          token: getStorage('token')
        },
        onSuccess: (response) => {
          wechatImg.value = response.data.virtualPath
          currentRow.value.wechatImg = response.data.virtualPath
        },
        onExceed: (_files, responses) => {
          wechatImg.value = responses[0].response.data.virtualPath
          currentRow.value.wechatImg = responses[0].response.data.virtualPath
        },
        slots: {
          default: () => (
            <>
              {wechatImg.value ? <img src={wechatImg.value} class="avatar" /> : null}
              {!wechatImg.value ? (
                <Icon class="avatar-uploader-icon" icon="ep:plus" size={28}></Icon>
              ) : null}
            </>
          )
        }
      }
    }
  },
  {
    field: 'createTime',
    label: '创建时间',
    minWidth: 180,
    table: {
      hidden: false
    },
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'action',
    width: '120px',
    label: '操作',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      hidden: false,
      fixed: 'right',
      slots: {
        default: (data: any) => {
          return (
            <ElButtonGroup>
              <ElTooltip content="编辑">
                <ElButton text icon={EditIcon} onClick={() => handleEdit(data.row)} />
              </ElTooltip>
              <ElTooltip content="删除">
                <ElButton text icon={DeleteIcon} type="danger" onClick={() => delData(data.row)} />
              </ElTooltip>
            </ElButtonGroup>
          )
        }
      }
    }
  }
]

// @ts-ignore
const getSchemas = () => {
  let localSchemas = appStore.getPageData['CompanyPage']
  if (localSchemas && localSchemas.schemas) {
    let localSchemasArr = localSchemas.schemas
    for (let i = 0; i < localSchemasArr.length; i++) {
      let item = localSchemasArr[i]
      let index = crudSchemas.findIndex((e) => {
        return e.field == item.field
      })
      if (index > 0) {
        set(crudSchemas[index], 'table.hidden', item.table.hidden)
      }
    }
  }
}
getSchemas()
let allSchemas = useCrudSchemas(crudSchemas).allSchemas
// 修改列设置后调用
const setSchemas = (schemas: CrudSchema[]) => {
  let arr = schemas.map((item) => {
    return {
      field: item.field,
      path: 'hidden',
      value: item.table ? item.table.hidden : false
    }
  })
  setColumn(arr)
}
const writeRef = ref<ComponentRef<typeof Write>>()

const handleEdit = (row: CompanyData) => {
  currentRow.value = row
  wechatImg.value = row.wechatImg
  formState.value = 'edit'
  dialogVisible.value = true
}

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  console.log(formData)
  if (formData) {
    delLoading.value = true
    try {
      if (formData.id) {
        let res = await updateTableApi(formData)
        if (res) {
          currentPage.value = 1
          getList()
        }
      } else {
        let res = await saveTableApi(formData)
        if (res) {
          currentPage.value = 1
          getList()
        }
      }
    } catch (error) {
    } finally {
      delLoading.value = false
      dialogVisible.value = false
    }
  }
}

const delLoading = ref(false)

const delData = async (row: CompanyData) => {
  if (!row.id) return
  id.value = row?.id
  delLoading.value = true
  await delList(unref(id).length).finally(() => {
    delLoading.value = false
  })
}

const handleAdd = () => {
  formState.value = 'add'
  currentRow.value = {
    wechatImg: '',
    companyName: ''
  }
  wechatImg.value = ''
  dialogVisible.value = true
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <TableSetting page="CompanyPage" :data="crudSchemas" @set-schemas="setSchemas" />
    </div>

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    />
  </ContentWrap>
  <Dialog v-model="dialogVisible" :title="formState == 'add' ? '新增' : '编辑'">
    <Write ref="writeRef" :form-schema="allSchemas.formSchema" :current-row="currentRow" />
    <template #footer>
      <ElButton type="primary" :loading="delLoading" @click="save">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
@/hooks/event/useEmitt

<style lang="less">
.uploadBtn {
  display: inline-block;
  margin-right: 12px;
}
.filePageUploader {
  width: 100%;
}
</style>
<style scoped>
.companyUploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style lang="less">
.companyUploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  img {
    width: 178px;
    height: 178px;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
}
</style>
