<script setup lang="tsx">
import { reactive, ref, unref, onMounted } from 'vue'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { ContentWrap } from '@/components/ContentWrap'
import { Dialog } from '@/components/Dialog'
import { BaseButton } from '@/components/Button'
import {
  FormInstance,
  ElMessage,
  ElSelect,
  ElOption,
  ElForm,
  ElFormItem,
  ElInput,
  ElDrawer,
  ElTable,
  ElTableColumn
} from 'element-plus'
import {
  getStoreUser,
  getMirror,
  getStoreList,
  addMirror,
  getMirrorDetail
} from '@/api/erp'
import { useRouter } from 'vue-router'
import { formatTime } from '@/utils'
// import Write from './components/Write.vue'

const { t } = useI18n()
useRouter()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const res = await getMirror({
      page: unref(currentPage) || 1,
      limit: unref(pageSize) || 10,
      ...unref(searchParams)
    })

    return {
      list: res.data.data,
      total: res.data.count || 0
    }
  }
})
onMounted(() => {
  getStore()
})

const { dataList, loading, total, currentPage, pageSize } = tableState
const { getList } = tableMethods

const storeLoading = ref(false)
const storeOptions = ref<any[]>([])
const getStore = async (query = '', id = '') => {
  try {
    storeLoading.value = true
    const res = await getStoreList({ page: 1, limit: 1000, name: query, id, store: 1 })
    if (res) {
      storeOptions.value = res.data.data.map((item) => {
        return {
          value: item.id,
          label: item.name
        }
      })
    } else {
      return []
    }
  } catch (error) {
    console.log(error)
  } finally {
    storeLoading.value = false
  }
}

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'id',
    label: 'ID',
    align: 'center',
    width: 70
  },
  {
    field: 'out',
    label: '门店',
    minWidth: 150,
    slots: {
      default: ({ row }: any) => {
        return <>{row.store?.name}</>
      }
    }
  },
  {
    field: 'create_admin_id',
    label: '创建人员',
    width: 200,
    slots: {
      default: ({ row }: any) => {
        return (
          <>
            <div>{row.cuser?.real_name || '-'}</div>
            <div>{row.create_time ? formatTime(row.create_time * 1000, 'yyyy-MM-dd') : ''}</div>
          </>
        )
      }
    }
  },
  {
    field: 'add_time_txt',
    label: '创建时间',
    minWidth: 230
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    width: 200,
    fixed: 'right',
    align: 'center',
    headerAlign: 'center',
    slots: {
      default: ({ row }: any) => {
        return (
          <>
            <BaseButton link size="small" type="primary" onClick={() => action('detail', row)}>
              详情
            </BaseButton>
          </>
        )
      }
    }
  }
])

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'store_id',
    label: '门店',
    component: 'Select',
    value: '',
    componentProps: {
      placeholder: '请选择',
      options: storeOptions
    }
  }
  // {
  //   field: 'name',
  //   label: '名称',
  //   component: 'Input',
  //   value: '',
  //   componentProps: {
  //     placeholder: '请输入门店名称'
  //   }
  // }
])

const searchParams = ref<{
  type?: string
  qtype?: string
}>({
  type: 'loss',
  qtype: 'store'
})
const setSearchParams = (data: any) => {
  searchParams.value = data
  getList()
}

const dialogTitle = ref('')
const actionType = ref('')
// const writeRef = useTemplateRef('writeRef')

// function arrayToObject(array) {
//     var obj = {};
//     for (var i = 0; i < array.length; i++) {
//         obj[i] = array[i];
//     }
//     return obj;
// }
const dialogVisibles = ref(false)
const dialogVisibless = ref(false)
const showInfo = ref({ store: { name: '' }, cuser: { real_name: '', phone: '' }, add_time_txt: '', body: [] })
const getMirrorInfo = async (id: number) => {
  const res = await getMirrorDetail(id)
  showInfo.value = res.data
  dialogVisibless.value = true
}

const action = async (type: string, row?: any) => {
  actionType.value = type
  if (type == 'detail') {
    getMirrorInfo(row.id)
  }
  if (type == 'add') {
    dialogTitle.value = t('exampleDemo.add')
    dialogVisibles.value = true
  }
}
const formData = ref({ create_admin_id: '', store_id: '' })
const adminOptions = ref<any[]>([])
const adminLoading = ref(false)
const rules = reactive({
  create_admin_id: [{ required: true, message: '请选择创建人', trigger: 'change' }],
  store_id: [{ required: true, message: '请选择门店', trigger: 'change' }]
})
const getAdmin = async () => {
  const res = await getStoreUser({
    page: 1,
    limit: 20,
    relation_id: formData.value.store_id || ''
  })
  adminLoading.value = true
  try {
    if (res) {
      adminOptions.value = res.data.map((item) => {
        return {
          value: item.id,
          label: item.real_name
        }
      })
      console.log(adminOptions.value, 'adminOptions.value')
    } else {
      return []
    }
  } catch (err) {
    console.log(err)
  }
}
const cancelClick = () => {
  dialogVisibles.value = false
  formData.value.create_admin_id = ''
  formData.value.store_id = ''
}
const confirmClick = async (formEl: FormInstance | undefined) => {
  if (!formEl) return []
  const valid = await formEl.validate((valid, fields) => {
    if (valid) {
    } else {
      for (const key in fields) {
        ElMessage.error(fields[key][0].message)
        return
      }
      console.log('error submit!', fields)
    }
  })
  if (valid) {
    const res = await addMirror(0, {
      create_admin_id: formData.value.create_admin_id,
      store_id: formData.value.store_id
    })
    if (res.status == 200) {
      ElMessage.success(res.msg)
      dialogVisibles.value = false
      formData.value.create_admin_id = ''
      formData.value.store_id = ''
      getList()
    }
  }
}

const formRef = ref<FormInstance>()
</script>

<template>
  <ContentWrap>
    <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />
    <div class="mb-10px">
      <BaseButton type="primary" @click="action('add')">{{ t('exampleDemo.add') }}</BaseButton>
    </div>
    <Table
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :columns="tableColumns"
      default-expand-all
      node-key="id"
      stripe
      :data="dataList"
      :loading="loading"
      @register="tableRegister"
      :pagination="{
        total
      }"
    />
  </ContentWrap>
  <Dialog v-model="dialogVisibles" :title="dialogTitle" width="500px" maxHeight="100px">
    <!-- <Record :cid="cid"></Record> -->
    <ElForm ref="formRef" :model="formData" :rules="rules" label-width="100px">
      <ElFormItem label="门店" prop="store_id">
        <ElSelect
          filterable
          remote
          reserve-keyword
          v-model="formData.store_id"
          :remote-method="getStore"
          remote-show-suffix
          placeholder="请选择门店"
        >
          <ElOption
            v-for="item in storeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="创建人员" prop="create_admin_id">
        <ElSelect
          filterable
          remote
          reserve-keyword
          v-model="formData.create_admin_id"
          :remote-method="getAdmin"
          remote-show-suffix
          placeholder="请选择审核人员"
        >
          <ElOption
            v-for="item in adminOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </ElSelect>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <div style="flex: auto">
        <BaseButton @click="cancelClick">取消</BaseButton>
        <BaseButton type="primary" @click="confirmClick(formRef)">确认</BaseButton>
      </div>
    </template>
  </Dialog>
  <ElDrawer direction="rtl" v-model="dialogVisibless" :title="dialogTitle" width="500px">
    <ElForm ref="formRefs" :model="showInfo" label-width="100px">
      <ElFormItem label="门店:" prop="store">
        <ElInput type="text" v-model="showInfo.store.name" disabled />
      </ElFormItem>
      <ElFormItem label="创建人:" prop="create_admin_id">
        <ElInput type="text" v-model="showInfo.cuser.real_name" disabled />
      </ElFormItem>
      <ElFormItem label="联系方式:" prop="create_admin_id">
        <ElInput type="text" v-model="showInfo.cuser.phone" disabled />
      </ElFormItem>
      <!--  -->
      <ElFormItem label="创建时间:" prop="add_time_txt">
        <ElInput type="text" v-model="showInfo.add_time_txt" disabled />
      </ElFormItem>
      <ElFormItem label="商品信息:" prop="body">
        <ElTable
          header-cell-class-name="bg-gray-100!"
          :data="showInfo.body"
          class="w-100%"
          :border="true"
          stripe
        >
        <ElTableColumn prop="id" label="ID"> </ElTableColumn>
        <ElTableColumn prop="store_name" label="名称"> </ElTableColumn>
        <ElTableColumn prop="stock" label="库存"> </ElTableColumn>
        <ElTableColumn prop="cost" label="成本"> </ElTableColumn>
        <ElTableColumn prop="xj" label="小计">
          <template #default="{ row }">
            <div>{{ (row.cost *  row.stock).toFixed(2)}}</div>
          </template>
        </ElTableColumn>
        </ElTable>
      </ElFormItem>
    </ElForm>
  </ElDrawer>
</template>
