<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 {
  ElDivider,
  ElMessage,
  ElMessageBox,
  ElTag,
  ElText,
  ElSelect,
  ElOption,
  ElForm,
  ElFormItem,
  ElInput,
  ElTable,
  ElTableColumn
} from 'element-plus'
import {
  getStoreUser,
  refuse,
  lossesAuth,
  refuseStock,
  wareLossAuth,
  getStoreList,
  getAdjust
} from '@/api/erp'
import { useRouter } from 'vue-router'
import { formatTime } from '@/utils'
// import Write from './components/Write.vue'

const { t } = useI18n()
const { push } = useRouter()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const res = await getAdjust({
      page: unref(currentPage) || 1,
      limit: unref(pageSize) || 10,
      ...unref(searchParams)
    })
    return {
      list: res.data.data,
      total: res.data.count || 0
    }
  }
})

onMounted(() => {
  getStore()
  getWare()
})

const storeLoading = ref(false)
const wareLoading = ref(false)

const storeOptions = ref<any[]>([])
const wareOptions = 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 getWare = async (query = '', id = '') => {
  try {
    wareLoading.value = true
    const res = await getStoreList({ page: 1, limit: 1000, name: query, id, type: 3 })
    if (res) {
      wareOptions.value = res.data.data.map((item) => {
        return {
          value: item.id,
          label: item.name
        }
      })
    } else {
      return []
    }
  } catch (error) {
    console.log(error)
  } finally {
    wareLoading.value = false
  }
}

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

const searchParams = ref<{
  adjust_type?: string
  wid?: string | number
  store_id?: string | number
}>({
  adjust_type: '1',
  store_id: '',
  wid: ''
})
const setSearchParams = (data: any) => {
  searchParams.value = data
  getList()
}

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'adjust_type',
    label: '类型',
    component: 'Select',
    value: '1',
    componentProps: {
      placeholder: '仓库调价',
      options: [
        {
          label: '仓库调价',
          value: '1'
        },
        {
          label: '门店调价',
          value: '0'
        }
      ]
    }
  },
  {
    field: 'store_id',
    label: '门店',
    component: 'Select',
    value: '',
    componentProps: {
      placeholder: '请选择',
      options: storeOptions
    }
  },
  {
    field: 'wid',
    label: '仓库',
    component: 'Select',
    value: '',
    componentProps: {
      placeholder: '请选择',
      options: wareOptions
    }
  }
  // {
  //   field: 'name',
  //   label: '名称',
  //   component: 'Input',
  //   value: '',
  //   componentProps: {
  //     placeholder: '请输入门店名称'
  //   }
  // }
])

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'id',
    label: 'ID',
    align: 'center',
    width: 70
  },
  {
    field: 'order_id',
    label: '调价单号',
    minWidth: 230
  },
  {
    field: 'out',
    label: '调价单位',
    minWidth: 150,
    slots: {
      default: ({ row }: any) => {
        console.log(row, 'row')
        if (row.adjust_type == 1) {
          return (
            <>
              <div>{row.Warehouse.name}</div>
            </>
          )
        } else {
          return (
            <>
              <div>{row.store?.name}</div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'stockinfo',
    label: '调价商品',
    minWidth: 200,
    slots: {
      default: ({ row }: any) => {
        if (row?.body?.length > 0) {
          if (row.store_id > 0) {
            return (
              <>
                {row.body.map((item) => {
                  return (
                    <>
                      <ElText class="mx-1 mr20" style={'margin-right: 10px'} type="primary">
                        {item.product_name + ' '}
                      </ElText>
                    </>
                  )
                })}
              </>
            )
          } else {
            return (
              <>
                {row.body.map((item) => {
                  return (
                    <>
                      <ElText class="mx-1 " style={'margin-right: 10px'} type="primary">
                        {item.product_name}
                      </ElText>
                    </>
                  )
                })}
              </>
            )
          }
        } else {
          return <></>
        }
      }
    }
  },
  {
    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: 'auth_admin_id',
    label: '审核人员',
    width: 200,
    slots: {
      default: ({ row }: any) => {
        return (
          <>
            <div>{row.auser?.real_name || '-'}</div>
            <div>{row.auth_time ? formatTime(row.auth_time * 1000, 'yyyy-MM-dd') : ''}</div>
          </>
        )
      }
    }
  },
  {
    field: 'status',
    label: '状态',
    width: 190,
    slots: {
      default: ({ row }: any) => {
        return (
          <>
            <ElTag
              class="mr-5px"
              type={row.status == -1 ? 'danger' : row.status == 0 ? 'warning' : 'success'}
            >
              {row.status == -1 ? '拒绝' : row.status == 0 ? '待审核' : '通过'}
            </ElTag>
          </>
        )
      }
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    width: 200,
    fixed: 'right',
    align: 'center',
    headerAlign: 'center',
    slots: {
      default: ({ row }: any) => {
        if (row.status == 0) {
          return (
            <>
              <BaseButton link size="small" type="primary" onClick={() => action('pass', row)}>
                通过
              </BaseButton>
              <ElDivider direction="vertical" />
              <BaseButton link size="small" type="danger" onClick={() => action('repass', row)}>
                拒绝
              </BaseButton>
            </>
          )
        } else {
          return (
            <>
              <BaseButton link size="small" type="primary" onClick={() => action('info', row)}>
                详情
              </BaseButton>
            </>
          )
        }
      }
    }
  }
])

const dialogVisible = ref(false)
const currentRow = ref()
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 authId = ref(0)
const storeId = ref(0)
const wid = ref(0)
const dialogVisibles = ref(false)
const dialogVisibless = ref(false)
const dialogVisiblesss = ref(false)
const dialogVisiblessss = ref(false)
const showInfo = ref(false)

const endItem = ref({ wid: '', store_id: '', info: [], out_order_id: '', id: 0 })
type storeOrWare = {
  name?: string
  phone?: number | string
}
type bodyGood = {
  product_id: number | string
}
type adminInfo = {
  real_name: string
}
type adjustItem = {
  Warehouse?: storeOrWare
  add_time?: number
  adjust_type?: number
  auser?: adminInfo
  auth_admin_id?: number
  auth_remark?: null | string
  auth_time?: number
  body: bodyGood[]
  create_admin_id?: number
  cuser?: adminInfo
  id: number
  order_id?: string
  status: number
  store?: storeOrWare
  store_id?: number
  type: number
  wid?: number
}
const adItem = ref<adjustItem>({
  Warehouse: {},
  adjust_type: 0,
  auth_admin_id: 0,
  auth_remark: null,
  auth_time: 0,
  body: [],
  create_admin_id: 0,
  id: 0,
  order_id: '',
  status: 0,
  store: {},
  store_id: 0,
  type: 0,
  wid: 0
})
const action = async (type: string, row?: any) => {
  actionType.value = type
  if (type == 'info') {
    adItem.value = row
    showInfo.value = true
  }
  if (type == 'repass') {
    endItem.value = row
    dialogVisibless.value = true
  }
  if (type == 'pass') {
    endItem.value = row
    dialogVisibles.value = true
  }
  if (type == 'out') {
    ElMessageBox.confirm('是否立即出库?', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        const re = await refuse({ id: row.id })
        if (re) {
          ElMessage({
            showClose: true,
            message: '处理成功',
            type: 'success'
          })
        }
        await getList()
      })
      .catch(() => {})
  }
  if (type == 'authCompute') {
    endItem.value = row
    dialogVisiblessss.value = true
  }
  if (type == 'compute') {
    endItem.value = row
    dialogVisiblesss.value = true
  }

  if (type == 'auth') {
    dialogTitle.value = '审核'
    authId.value = row.id * 1
    storeId.value = row.up_store_id || 0
    wid.value = row.up_wid || 0
    dialogVisibles.value = true
  }
  if (type == 'add') {
    // dialogTitle.value = t('exampleDemo.add')
    // currentRow.value = undefined
    push(`/erp/adjust_edit/${type}/${row?.id || 0}`)
  }
  if (type == 'edit') {
    dialogTitle.value = t('exampleDemo.edit')
    currentRow.value = {
      // roles: row.roles,
      wid: row.wid,
      type: row.type,
      id: row.id,
      name: row.name,
      is_show: row.is_show == 1 ? true : false,
      introduction: row.introduction,
      address: row.address,
      area: row.area,
      city: row.city,
      province: row.province,
      detailed_address: row.detailed_address,
      latitude: row.latitude,
      logo: [row.logo],
      longitude: row.longitude,
      manager_name: row.manager_name,
      phone: row.phone,
      product_verify_status: row.product_verify_status == 1 ? true : false,
      product_status: row.product_status == 1 ? true : false,
      valid_range: row.valid_range,
      slide_images: row.slide_images_chs,
      auth_code: row.auth_code,
      auth_code_end_time: row.auth_code_end_time,
      ppid: row.appid,
      loss_sale: row.loss_sale == 1,
      receiver_uid: row.receiver_uid,
      huifu_id: row.huifu_id,
      appsecret: row.appsecret,
      cost: row.cost,
      roles: row.roles * 1
    }
    console.log(currentRow, 'currentRow')
    dialogVisible.value = true
  }
}
const formData = ref({ auth_admin_id: '', auth_status: 1, freight: '', refuse_remark: '' })
const adminOptions = ref<any[]>([])
const adminLoading = ref(false)
const rules = reactive({
  auth_admin_id: [{ required: true, message: '请选择审核员', trigger: 'change' }],
  refuse_remark: [{ required: true, message: '请填写拒绝原因' }]
})
const getAdmin = async () => {
  const res = await getStoreUser({
    page: 1,
    limit: 20,
    relation_id: endItem.value.store_id ? endItem.value.store_id : endItem.value.wid
  })
  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.auth_admin_id = ''
  formData.value.freight = ''
  formData.value.refuse_remark = ''
  endItem.value = { wid: '', store_id: '', id: 0, info: [], out_order_id: '' }
}
const cancelClicks = () => {
  dialogVisibless.value = false
  cancelClick()
}
const confirmClick = async () => {
  if (!formData.value.auth_admin_id) {
    return ElMessage.error('请选择审核人员')
  }
  // if (formData.value.status == 1 && !formData.value.purchasing_person_admin_id) {
  //   return ElMessage.error('请选择采购人员')
  // }
  if (endItem.value.wid) {
    const res = await wareLossAuth(endItem.value.id, {
      create_admin_id: formData.value.auth_admin_id,
      wid: endItem.value.wid || '',
      store_id: endItem.value.store_id || '',
      status: 1
    })
    if (res.status == 200) {
      ElMessage.success('审核完成')
      getList()
      cancelClick()
    }
  } else {
    const res = await lossesAuth(endItem.value.id, {
      info: endItem.value.info,
      create_admin_id: formData.value.auth_admin_id,
      store_id: endItem.value.store_id,
      out_order_id: endItem.value.out_order_id
    })
    if (res.status == 200) {
      ElMessage.success('审核完成')
      getList()
      cancelClick()
    }
  }
}

const confirmClicks = async () => {
  if (!formData.value.refuse_remark) {
    return ElMessage.error('请选择拒绝原因')
  }
  if (!formData.value.auth_admin_id) {
    return ElMessage.error('请填写审核人')
  }
  let res
  if (endItem.value.wid) {
    res = await wareLossAuth(endItem.value.id, {
      create_admin_id: formData.value.auth_admin_id,
      wid: endItem.value.wid || '',
      status: -1,
      auth_remark: formData.value.refuse_remark
    })
  } else {
    res = await refuseStock(endItem.value.id, {
      auth_status: -1,
      auth_remark: formData.value.refuse_remark,
      create_admin_id: formData.value.auth_admin_id,
      store_id: endItem.value.store_id || ''
    })
  }
  if (res.status == 200) {
    ElMessage.success('处理完成')
    getList()
    cancelClicks()
  }
}
</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="auth_admin_id">
        <ElSelect
          filterable
          remote
          reserve-keyword
          v-model="formData.auth_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">确认</BaseButton>
      </div>
    </template>
  </Dialog>
  <Dialog v-model="dialogVisibless" :title="dialogTitle" width="500px" maxHeight="150px">
    <ElForm ref="formRef" :model="formData" :rules="rules" label-width="100px">
      <ElFormItem label="审核人员" prop="auth_admin_id">
        <ElSelect
          filterable
          remote
          reserve-keyword
          v-model="formData.auth_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>
      <ElFormItem prop="refuse_remark" label="拒绝原因">
        <ElInput type="textarea" v-model="formData.refuse_remark" />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <div style="flex: auto">
        <BaseButton @click="cancelClick">取消</BaseButton>
        <BaseButton type="primary" @click="confirmClicks">确认</BaseButton>
      </div>
    </template>
  </Dialog>
  <Dialog v-model="showInfo" title="调价" width="900px">
    <div id="dc">
      <div class="section">
        <div class="text-center title pb5">调价详情</div>
        <div class="top-tit">
          <div class="item mb10">
            <div class=""
              ><span class="name">调价单号：</span><span>{{ adItem.order_id }}</span></div
            >
            <div class="val"></div>
          </div>
          <div class="item mb10" v-if="adItem?.wid && adItem?.Warehouse?.name">
            <div class=""
              ><span class="name">调价单位：</span
              ><span>{{ adItem.Warehouse.name || '' }}</span></div
            >
          </div>
          <div class="item mb10" v-if="adItem?.wid">
            <div class=""
              ><span class="name">联系电话：</span><span>{{ adItem.Warehouse?.phone }}</span></div
            >
            <div class="val"></div>
          </div>
          <div class="item mb10" v-if="adItem?.store_id">
            <div class=""
              ><span class="name">调价单位：</span><span>{{ adItem?.store?.name }}</span></div
            >
            <div class="val"></div>
          </div>
          <div class="item  mb10" v-if="adItem?.store">
            <div class=""
              ><span class="name">联系电话：</span><span>{{ adItem?.store?.phone }}</span></div
            >
          </div>
        </div>
        <div class="" v-if="adItem?.wid">
          <ElTable :data="adItem.body" style="width: 100%" :border="true">
            <el-table-column label="id" prop="product_id" />
            <el-table-column label="商品名称" prop="product_name" />
            <el-table-column label="价格" prop="price" />
          </ElTable>
        </div>
        <div class="" v-if="adItem?.store_id">
          <ElTable :data="adItem.body" style="width: 100%" :border="true">
            <ElTableColumn type="expand">
              <template #default="props">
                <div m="4" class="pl20">
                  <ElTable :data="props.row.specs" :border="true">
                    <ElTableColumn label="单位" prop="name" />
                    <ElTableColumn label="价格" prop="price" />
                    <ElTableColumn label="VIP价格" prop="price_1" />
                    <ElTableColumn label="金卡价格" prop="price_2" />
                    <ElTableColumn label="钻卡价格" prop="price_3" />
                  </ElTable>
                </div>
              </template>
            </ElTableColumn>
            <el-table-column label="id" prop="product_id" />
            <el-table-column label="商品名称" prop="product_name" />
          </ElTable>
        </div>
        <div class="btm-tip">
          <div class="itemt">
            <span class="name">货品数：</span>
            <span>{{ adItem.body.length }}</span>
          </div>
          <div class="itemt">
            <span class="name">创建人：</span>
            <span>{{ adItem?.cuser?.real_name }}</span>
          </div>
          <div class="itemt">
            <span class="name">审核人：</span>
            <span>{{ adItem?.auser?.real_name }}</span>
          </div>
        </div>
      </div>
    </div>
    <!-- <template #footer>
      <div style="flex: auto">
        <BaseButton type="primary" v-print="printobj">打印</BaseButton>
      </div>
    </template> -->
  </Dialog>
</template>

<style>
@media print {
  .section {
    page-break-before: always;
    margin-top: 0;
  }
}
.bold {
  font-weight: bold;
}
#dc {
  font-size: 14px;
  page-break-before: always;
  padding: 10px;
  position: relative;
  padding-bottom: 100px;
}
.title {
  font-size: 18px;
  font-weight: bold;
  color: #000000;
}
.top-tit {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  padding: 20px 0 10px;
}
.item {
  width: 50%;
  /* margin-bottom: 10px; */
}
.mb10 {
  margin-bottom: 10px;
}
.items {
  width: 100% !important;
}
.name {
  font-weight: bold;
  color: #000000;
}
.table {
  width: 98%;
  text-align: center;
  border-top: 1px solid #000;
  /* border-left: 1px solid #000; */
}
.table > .tr {
  display: flex;
  flex-wrap: wrap;
}
.table .tr > .item {
  padding: 5px 10px;
  /* border-right: 1px solid #000; */
  border-bottom: 1px solid #000;
  display: flex;
  justify-content: center;
  align-items: center;
}
.w30 {
  width: 30%;
}
.w20 {
  width: 20%;
}
.w10 {
  width: 10%;
}
.w5 {
  width: 5%;
}
.w15 {
  width: 15%;
}
.table .th {
  color: #000000;
  padding: 10px 0;
  border-left: 1px solid #000000;
  border-top: 1px solid #000000;
  min-width: 60px;
}

.table .td {
  padding: 5px 3px;
  border-left: 1px solid #000000;
  border-top: 1px solid #000000;
}
@media print {
  body,
  html,
  .previewPageBox {
    height: auto !important;
    overflow: visible !important;
  }

  .previewPageBox {
    position: relative !important;
  }
}
.btm-tip {
  display: flex;
  width: 100%;
  flex-wrap: wrap;
  padding-top: 150px;
}
.btm-tip .itemt {
  width: 33.3%;
  margin-bottom: 10px;
}
</style>
