<script setup lang="tsx">
import { reactive, ref, unref, onMounted } from 'vue'
import { addCoupon, editCoupon } from '@/api/marketing'
import { wantList } from '@/api/erp'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { ContentWrap } from '@/components/ContentWrap'
import { Dialog } from '@/components/Dialog'
import { BaseButton } from '@/components/Button'
import {
  ElDivider,
  ElMessage,
  ElMessageBox,
  ElTag,
  ElForm,
  ElFormItem,
  ElSelect,
  ElOption,
  ElRadioGroup,
  ElRadio,
  ElText
} from 'element-plus'
import Write from './components/Write.vue'
import { useRouter } from 'vue-router'
import { getStoreUser,authWant, delWant,getStoreList } from '@/api/erp'
import { formatTime } from '@/utils'
import { FormSchema } from '@/components/Form'
import { Search } from '@/components/Search'

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

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

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

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'id',
    label: 'ID',
    align: 'center',
    width: 70
  },
  {
    field: 'want_order_id',
    label: '要货单号',
    minWidth: 220
  },
  {
    field: 'mystore',
    label: '门店',
    width: 200,
    slots: {
      default: ({ row }: any) => {
        return <>{row.mystore.name}</>
      }
    }
  },
  {
    field: 'from',
    label: '要货来源',
    width: 200,
    slots: {
      default: ({ row }: any) => {
        return <>{row.ware?.name || row.store?.name}</>
      }
    }
  },
  {
    field: 'info',
    label: '要货商品',
    minWidth: 200,
    slots: {
      default: ({ row }: any) => {
        return (
          <>
            {row.info.map((item) => {
              return (
                <>
                  <div>
                    {item.product_name}
                    <ElText class="mx-1" type="primary"> {item.want_product_num * 1}</ElText>
                    {item.suk}
                  </div>
                </>
              )
            })}
          </>
        )
      }
    }
  },
  {
    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) => {
        if (row.status == 3) {
          return (
            <>
              <ElTag>全部完成</ElTag>
            </>
          )
        } else {
          return (
            <>
              <ElTag
                class="mr-5px"
                type={
                  row.status == -1
                    ? 'danger'
                    : row.status == 0
                      ? 'warning'
                      : row.status == 1
                        ? 'success'
                        : row.status == 2
                          ? 'info'
                          : 'success'
                }
              >
                {row.status == -1
                  ? '拒绝'
                  : row.status == 0
                    ? '待审核'
                    : row.status == 1
                      ? '通过'
                      : row.status == 2
                        ? '部分完成'
                        : '全部完成'}
              </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('auth', row)}>
                审核
              </BaseButton>
              <ElDivider direction="vertical" />
              <BaseButton link size="small" type="danger" onClick={() => delAction(row)}>
              删除
              </BaseButton>
              <ElDivider direction="vertical" />
              <BaseButton link size="small" type="primary" onClick={() => action('print', row)}>
                打印
              </BaseButton>
            </>
          )
        } else {
          return <>
              <BaseButton link size="small" type="primary" onClick={() => action('print', row)}>
                打印
              </BaseButton></>
        }
      }
    }
  }
])



const dialogVisible = ref(false)
const dialogVisibles = ref(false)

const currentRow = ref()
const cid = ref(0)

const dialogTitle = ref('')
const actionType = ref('')
const saveLoading = ref(false)
const adminOptions = ref<any[]>([])
const adminLoading = ref(false)
const getAdmin = async () => {
  const res = await getStoreUser({ page: 1, limit: 20, relation_id: storeId.value })
  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)
  }
}

// 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 prDialogVisible = ref(false)
const prItem = ref<any>({})
const action = async (type: string, row?: any) => {
  if (type == 'print') {
    prDialogVisible.value = true
    prItem.value = row
  }
  actionType.value = type
  if (type == 'add') {
    // dialogTitle.value = t('exampleDemo.add')
    // currentRow.value = undefined
    // dialogVisible.value = true
    push(`/erp/want_edit/${type}/${row?.id || 0}`)
  }
  if (type == 'list') {
    dialogTitle.value = '领取记录'
    cid.value = row.id * 1
    dialogVisibles.value = true
  }
  if (type == 'auth') {
    dialogTitle.value = '审核'
    authId.value = row.id * 1
    storeId.value = row.store_id
    dialogVisibles.value = true
  }
}
const delAction = (row: any) => {
  ElMessageBox.confirm('删除后无法恢复，是否删除?', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const re = await delWant(row.id)
      if (re) {
        ElMessage({
          showClose: true,
          message: '删除成功',
          type: 'success'
        })
      }
      await getList()
    })
    .catch(() => {})
}
const save = async (coupon) => {
  console.log('zhe', coupon)
  const data = {
    type: coupon.type,
    title: coupon.title,
    coupon_price: coupon.coupon_price,
    use_min_price: coupon.use_min_price,
    coupon_time: coupon.coupon_time,
    sort: coupon.sort,
    status: coupon.status,
    category_id: coupon.category_id || ''
  }
  try {
    if (actionType.value === 'edit') {
      await editCoupon(data)
    } else if (actionType.value === 'add') {
      await addCoupon(data)
    }
    ElMessage({
      showClose: true,
      message: '保存成功',
      type: 'success'
    })
    getList()
    saveLoading.value = false
    dialogVisible.value = false
  } catch (error) {
    console.log(error)
  } finally {
    saveLoading.value = false
  }
  // }
}
// const release = async (coupon) => {
//   // release
//   console.log('发布', coupon)

//   const data = {
//     start_time: coupon.start_time,
//     end_time: coupon.end_time,
//     is_permanent: coupon.is_permanent,
//     total_count: coupon.total_count,
//     is_full_give: coupon.is_full_give,
//     id: coupon.id,
//     full_reduction: coupon.full_reduction,
//     status: coupon.status,
//     is_give_subscribe: coupon.is_give_subscribe
//   }
//   try {
//     await releaseCoupon(data)
//     ElMessage({
//       showClose: true,
//       message: '发布成功',
//       type: 'success'
//     })
//     getList()
//     saveLoading.value = false
//     dialogVisibles.value = false
//   } catch (error) {}
// }
const formData = ref({ auth_admin_id: '' ,status: 1})
const rules = reactive({
  auth_admin_id: [{ required: true, message: '请选择审核员', trigger: 'change' }]
})
const cancelClick = ()=> {
  dialogVisibles.value = false
  authId.value = 0
  storeId.value = 0
  formData.value.auth_admin_id = ''
  formData.value.status = 1
}
const confirmClick = async ()=> {
  if(!formData.value.auth_admin_id) {
    return ElMessage.error('请选择审核人员')
  }
const res = await authWant(authId.value,formData.value)
if(res.status == 200) {
  ElMessage.success('审核完成')
  getList()
  cancelClick()
}
}

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 searchSchema = reactive<FormSchema[]>([
  {
    field: 'want_order_id',
    label: '要货单号',
    component: 'Input',
    value: '',
    componentProps: { placeholder: '请输入要货单号' }
  },
  {
    field: 'store_id',
    label: '门店',
    component: 'Select',
    value: '',
    componentProps: {
      placeholder: '请选择',
      options: storeOptions
    }
  },
  {
    field: 'up_wid',
    label: '仓库',
    component: 'Select',
    value: '',
    componentProps: {
      placeholder: '请选择',
      options: wareOptions
    }
  },
  {
    field: 'status',
    label: '状态',
    component: 'Select',
    value: -3,
    componentProps: {
      placeholder: '全部',
      options: [
        {
          label: '全部',
          value: -3
        },
        {
          label: '拒绝',
          value: -1
        },
        {
          label: '待审核',
          value: 0
        },
        {
          label: '通过',
          value: 1
        },
        {
          label: '部分完成',
          value: 2
        },
        {
          label: '全部完成',
          value: 3
        }
      ]
    }
  }
])

const searchParams = ref<{
  status: number
}>({
  status: -3
})
const setSearchParams = (data: any) => {
  searchParams.value = data
  getList()
}
const getTime = () => {
  let time = new Date().getTime()
  return formatTime(time, 'yyyy-MM-dd HH:mm:ss')
}
const getLen = () => {
  let sum = 0
  prItem.value.info.forEach((item) => {
    console.log(item.product_num)
      sum += item.want_product_num * 1
  })
  return sum
}
const printobj = ref({
  id: 'dc',
  popTitle: '好的打印标题',
  extraCss:
    'https://cdn.bootcdn.net/ajax/libs/animate.css/4.1.1/animate.compat.css, https://cdn.bootcdn.net/ajax/libs/hover.css/2.3.1/css/hover-min.css',
  extraHead: '<meta http-equiv="content-language" content="zh-cn" />',
  beforeOpenCallback(vue) {
    vue.printLoading = true
    console.log('打开之前')
  },
  openCallback(vue) {
    vue.printLoading = false
    console.log('执行了打印')
  }
})

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

</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="dialogVisible" :title="dialogTitle" width="800px" maxHeight="500px">
    <Write ref="writeRef" :current-row="currentRow" @addCoupon="save" />
    <!-- <template #footer>
      <BaseButton type="primary" :loading="saveLoading" @click="save">
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template> -->
  </Dialog>
  <Dialog v-model="dialogVisibles" :title="dialogTitle" width="500px" maxHeight="120px">
    <!-- <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>
      <ElFormItem label="审核状态" prop="status">
        <ElRadioGroup v-model="formData.status" class="ml-4">
          <ElRadio :label="1" size="large" >通过</ElRadio>
          <ElRadio :label="-1" size="large">拒绝</ElRadio>
        </ElRadioGroup>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <div style="flex: auto">
        <BaseButton @click="cancelClick">取消</BaseButton>
        <BaseButton type="primary" @click="confirmClick">确认</BaseButton>
      </div>
    </template>
  </Dialog>
  <!--  -->
  <Dialog v-model="prDialogVisible" title="打印">
    <div id="dc">
      <div class="section">
        <div class="text-center title">要货单</div>
        <div class="top-tit">
          <div class="item mb10">
            <div class=""
              ><span class="name">要货单号：</span><span>{{ prItem.want_order_id }}</span></div
            >
            <div class="val"></div>
          </div>
          <div class="item mb10" v-if="prItem?.mystore && prItem.mystore.name">
            <div class=""
              ><span class="name">要货单位：</span><span>{{ prItem?.mystore.name || '' }}</span></div
            >
          </div>
          <div class="item mb10" v-if="prItem?.mystore">
            <div class=""
              ><span class="name">联系电话：</span><span>{{ prItem.mystore.phone }}</span></div
            >
            <div class="val"></div>
          </div>
          <div class="item mb10" v-if="prItem?.ware">
            <div class=""
              ><span class="name">出货单位：</span><span>{{ prItem.ware.name }}</span></div
            >
            <div class="val"></div>
          </div>
          <div class="item mb10" v-if="prItem?.stroe">
            <div class=""
              ><span class="name">出货单位：</span><span>{{ prItem.stroe.name }}</span></div
            >
            <div class="val"></div>
          </div>
          <div class="item items mb10" v-if="prItem?.store">
            <div class=""
              ><span class="name">收货地址：</span><span>{{ prItem.store.address }}</span></div
            >
          </div>
        </div>
        <div class="table">
          <div class="tr">
            <div class="item w10">序号</div>
            <div class="item w20">编号</div>
            <div class="item w30">商品</div>
            <div class="item w20">数量</div>
            <div class="item w20">单位</div>
          </div>
          <div class="tr" v-for="(item, index) in prItem.info">
            <div class="item w10">{{ index + 1 }}</div>
            <div class="item w20">{{ item.bar_code }}</div>
            <div class="item w30">{{ item.product_name }}</div>
            <div class="item w20">{{
              item.want_product_num}}</div>
            <div class="item w20">{{ item.suk }}</div>
          </div>
        </div>
        <div class="btm-tip">
          <div class="itemt">
            <span class="name">货品数：</span>
            <span>{{ prItem.info.length }}</span>
          </div>
          <div class="itemt">
            <span class="name">数量：</span>
            <span>{{ getLen() }}</span>
          </div>
          <div class="itemt">
            <span class="name">审核人：</span>
            <span>{{ prItem.auth_admin_id ? prItem.auser.real_name : '' }}</span>
          </div>
          <div class="itemt">
            <span class="name">仓管员签字：</span>
            <span></span>
          </div>
          <div class="itemt">
            <span class="name">财务员签字：</span>
            <span></span>
          </div>
          <div class="itemt">
            <span>打印时间：</span>
            <span>{{ getTime() }}</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%;
}
.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>
