<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <Search
      :schema="Q2.allSchemas.searchSchema"
      @search="setSearchParams"
      @reset="setSearchParams"
    />
  </ContentWrap>

  <!-- 列表头部 -->
  <TableHead
    :HeadButttondata="HeadButttondata"
    @button-base-click="buttonBaseClick"
    :routeName="routeName"
    @updataTableColumns="updataTableColumns"
    @searchFormClick="searchFormClick"
    :allSchemas="Q2.allSchemas"
  />

  <!-- 列表 -->
  <ContentWrap>
    <Table
      :columns="tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :pagination="{
        total: tableObject.total
      }"
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      v-model:sort="tableObject.sort"
    >
      <template #number="{ row }">
        <el-button type="primary" link @click="openDetail(row, '代码', row.number)">
          <span>{{ row.number }}</span>
        </el-button>
      </template>
      <template #action="{ row }">
        <ButtonBase
          :Butttondata="butttondata(row)"
          @button-base-click="buttonTableClick($event, row)"
        />
      </template>
    </Table>
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <BasicForm
    ref="basicFormRef"
    @success="formsSuccess"
    :rules="Q2Rules"
    :formAllSchemas="Q2.allSchemas"
    :apiUpdate="Q2Api.updateQ2"
    :apiCreate="Q2Api.createQ2"
    @searchTableSuccess="searchTableSuccess"
    :isBusiness="false"
    @onChange="onChange"
  >
  <template #searchQuerypurchaseReceiptNumber>
      <el-form :inline="true">
        <el-form-item label="供应商物料代码">
          <el-input v-model="basicFormRef.formRef.formModel.itemCode" placeholder="请输入供应商" disabled></el-input>
        </el-form-item>
        <el-form-item label="供应商代码">
          <el-input v-model="basicFormRef.formRef.formModel.supplierCode" placeholder="请输入物料号" disabled></el-input>
        </el-form-item>
      </el-form>
  </template>
  </BasicForm>

  <!-- 详情 -->
  <Detail ref="detailRef" :isBasic="true" :allSchemas="Q2.allSchemas" />

  <!-- 导入 -->
  <ImportForm
    ref="importFormRef"
    url="/basic/Q2/import"
    :importTemplateData="importTemplateData"
    @success="importSuccess"
  />
</template>

<script setup lang="ts">
import download from '@/utils/download'
import { Q2, Q2Rules } from './inspectionQ2.data'
import * as Q2Api from '@/api/qms/inspectionQ2'
import * as defaultButtons from '@/utils/disposition/defaultButtons'
import TableHead from '@/components/TableHead/src/TableHead.vue'
import ImportForm from '@/components/ImportForm/src/ImportForm.vue'
import Detail from '@/components/Detail/src/Detail.vue'
import * as StdcostpriceApi from '@/api/wms/stdcostprice'
import { formatDate } from '@/utils/formatTime'
import * as SupplieritemApi from '@/api/wms/supplieritem'
import * as SupplierApi from '@/api/wms/supplier'
import * as ItembasicApi from '@/api/wms/itembasic'
import { useUserStore } from '@/store/modules/user'
import { usePageLoading } from '@/hooks/web/usePageLoading'
const { loadStart, loadDone } = usePageLoading()
const userStore = useUserStore()

defineOptions({ name: 'InspectionQ2' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const route = useRoute() // 路由信息
const routeName = ref()
routeName.value = route.name
const tableColumns = ref(Q2.allSchemas.tableColumns)

// 查询页面返回
const priceObj = ref()
const searchTableSuccess = (formField, searchField, val, formRef) => {
  nextTick(async () => {
    const setV = {}
    if (formField == 'supplierCode') {
      setV['purchaseReceiptNumber'] = ''
      const supplierParams = {
        by: 'ASC',
        filters: [{ column: 'code', action: '==', value: val[0].supplierCode }],
        pageNo: 1,
        pageSize: 500,
        sort: ''
      }
      supplierParams.isSearch = true
      SupplierApi.getSupplierPage(supplierParams).then((res) => {
        if (res.list?.length > 0) {
          formRef.setValues({
            supplierName: res.list[0].name
          })
        }
      })
      setV[formField] = val[0][searchField]
      formRef.setValues(setV)
    }

    if (formField == 'purchaseReceiptNumber') {
      let result = ''
      for (var i = 0; i < val.length; i++) {
        result += val[i].number + ','
      }
      if (result.endsWith(',')) {
        result = result.substring(0, result.length - 1)
      }
      setV['purchaseReceiptNumber'] = result
      formRef.setValues(setV)
    }

    if (formField == 'lightItemCode') {
      setV['lightItemCode'] = val[0].code
      setV['lightItemName'] = val[0].name
      setV[formField] = val[0][searchField]
      formRef.setValues(setV)
    }

    if (formField == 'costCode') {
      setV['costCode'] = val[0].costcentreCode
      setV[formField] = val[0][searchField]
      formRef.setValues(setV)
    }

    if (formField == 'itemCode') {
      setV['SupplierCode'] = ''
      setV['SupplierName'] = ''
      setV['itemName'] = ''
      setV['standardCostPrice'] = ''
      setV['lightQty'] = 0
      setV['claimAmount'] = 0
      setV['otherclaimAmount'] = 0
      setV['summaryAmount'] = 0
      setV['disbursementAmount'] = 0
      setV['remainingAmount'] = 0
      setV['purchaseReceiptNumber'] = ''
      setV['uom'] = val[0].supplierUom

      Q2Api.getEmail().then((res) => {
        if (res) {
          formRef.setValues({
            cashierEmail: res
          })
        }
      })

      const supplieritemParams = {
        by: 'ASC',
        filters: [{ column: 'itemCode', action: '==', value: val[0].itemCode }],
        pageNo: 1,
        pageSize: 500,
        sort: ''
      }
      supplieritemParams.isSearch = true
      SupplieritemApi.getSupplieritemPage(supplieritemParams).then((res) => {
        if (res.list?.length > 0) {
          formRef.formModel.supplierCode = res.list[0].supplierCode
          formRef.formModel.supplierName = res.list[0].supplierName
          Q2.allSchemas.formSchema.forEach((item) => {
            if (item.field == 'supplierCode') {
              item.componentProps.options = res.list
            }
          })
        }
      })
      const itembasicParams = {
        by: 'ASC',
        filters: [{ column: 'code', action: '==', value: val[0].itemCode }],
        pageNo: 1,
        pageSize: 500,
        sort: ''
      }

      itembasicParams.isSearch = true
      ItembasicApi.getItembasicPage(itembasicParams).then((res) => {
        if (res.list?.length > 0) {
          formRef.setValues({
            itemName: res.list[0].name
          })
        }
      })

      const params2 = {
        by: 'ASC',
        filters: [{ column: 'itemCode', action: '==', value: val[0].itemCode }],
        pageNo: 1,
        pageSize: 500,
        sort: ''
      }
      params2.isSearch = true
      StdcostpriceApi.getStdcostpricePage(params2).then((res) => {
        if (res.list?.length > 0) {
          priceObj.value = res.list[0]
          formRef.setValues({
            standardCostPrice: priceObj.value.price
          })
        }
      })

      setV[formField] = val[0][searchField]
      formRef.setValues(setV)
    }
  })
}

const onChange = (field, e) => {
  if (field == 'lightQty') {
    basicFormRef.value.formRef.formModel.claimAmount = (
      parseFloat(basicFormRef.value.formRef.formModel.lightQty) *
      parseFloat(basicFormRef.value.formRef.formModel.standardCostPrice) *
      parseFloat(basicFormRef.value.formRef.formModel.claimMultiple)
    ).toFixed(6)
    basicFormRef.value.formRef.formModel.summaryAmount = (
      parseFloat(basicFormRef.value.formRef.formModel.claimAmount) +
      parseFloat(basicFormRef.value.formRef.formModel.otherclaimAmount)
    ).toFixed(6)
    basicFormRef.value.formRef.formModel.remainingAmount = (
      parseFloat(basicFormRef.value.formRef.formModel.summaryAmount) -
      parseFloat(basicFormRef.value.formRef.formModel.disbursementAmount)
    ).toFixed(6)
  }
  if (field == 'claimMultiple') {
    basicFormRef.value.formRef.formModel.claimAmount = (
      parseFloat(basicFormRef.value.formRef.formModel.lightQty) *
      parseFloat(basicFormRef.value.formRef.formModel.standardCostPrice) *
      parseFloat(basicFormRef.value.formRef.formModel.claimMultiple)
    ).toFixed(6)
    basicFormRef.value.formRef.formModel.summaryAmount = (
      parseFloat(basicFormRef.value.formRef.formModel.claimAmount) +
      parseFloat(basicFormRef.value.formRef.formModel.otherclaimAmount)
    ).toFixed(6)
    basicFormRef.value.formRef.formModel.remainingAmount = (
      parseFloat(basicFormRef.value.formRef.formModel.summaryAmount) -
      parseFloat(basicFormRef.value.formRef.formModel.disbursementAmount)
    ).toFixed(6)
  }
  if (field == 'otherclaimAmount') {
    basicFormRef.value.formRef.formModel.summaryAmount = (
      parseFloat(basicFormRef.value.formRef.formModel.claimAmount) +
      parseFloat(basicFormRef.value.formRef.formModel.otherclaimAmount)
    ).toFixed(6)
    basicFormRef.value.formRef.formModel.remainingAmount = (
      parseFloat(basicFormRef.value.formRef.formModel.summaryAmount) -
      parseFloat(basicFormRef.value.formRef.formModel.disbursementAmount)
    ).toFixed(6)
  }
  if (field == 'claimAmount') {
    basicFormRef.value.formRef.formModel.summaryAmount = (
      parseFloat(basicFormRef.value.formRef.formModel.claimAmount) +
      parseFloat(basicFormRef.value.formRef.formModel.otherclaimAmount)
    ).toFixed(6)
    basicFormRef.value.formRef.formModel.remainingAmount = (
      parseFloat(basicFormRef.value.formRef.formModel.summaryAmount) -
      parseFloat(basicFormRef.value.formRef.formModel.disbursementAmount)
    ).toFixed(6)
  }

  if (field == 'disbursementAmount') {
    basicFormRef.value.formRef.formModel.remainingAmount = (
      parseFloat(basicFormRef.value.formRef.formModel.summaryAmount) -
      parseFloat(basicFormRef.value.formRef.formModel.disbursementAmount)
    ).toFixed(6)
  }

  if (field == 'supplierCode') {
    basicFormRef.value.formRef.formModel.supplierName = ''
    const paramsCustomer = {
      by: 'ASC',
      filters: [
        { column: 'code', action: '==', value: basicFormRef.value.formRef.formModel.supplierCode }
      ],
      pageNo: 1,
      pageSize: 500,
      sort: ''
    }
    paramsCustomer.isSearch = true
    SupplierApi.getSupplierPage(paramsCustomer).then((res) => {
      if (res.list?.length > 0) {
        basicFormRef.value.formRef.formModel.supplierName = res.list[0].name
      }
    })
  }
}

// 字段设置 更新主列表字段
const updataTableColumns = (val) => {
  tableColumns.value = val
}

const { tableObject, tableMethods } = useTable({
  getListApi: Q2Api.getQ2Page // 分页接口
})

// 获得表格的各种操作
const { getList, setSearchParams } = tableMethods

// 列表头部按钮
const HeadButttondata = [
  defaultButtons.defaultAddBtn({ hasPermi: 'qms:Q2:create' }), // 新增
  defaultButtons.defaultImportBtn({ hasPermi: 'qms:Q2:import' }), // 导入
  defaultButtons.defaultExportBtn({ hasPermi: 'qms:Q2:export' }), // 导出
  defaultButtons.defaultFreshBtn(null), // 刷新
  defaultButtons.defaultFilterBtn(null), // 筛选
  defaultButtons.defaultSetBtn(null) // 设置
  // {
  //   label: '自定义扩展按钮',
  //   name: 'zdy',
  //   hide: false,
  //   type: 'primary',
  //   icon: 'Select',
  //   color: ''
  // },
]

// 头部按钮事件
const buttonBaseClick = (val, item) => {
  if (val == 'add') {
    // 新增
    openForm('create')
  } else if (val == 'import') {
    // 导入
    handleImport()
  } else if (val == 'export') {
    // 导出
    handleExport()
  } else if (val == 'refresh') {
    // 刷新
    getList()
  } else if (val == 'filtrate') {
    // 筛选
  } else {
    // 其他按钮
    console.log('其他按钮', item)
  }
}

const isShowMainButton = (row, val) => {
  if (val.indexOf(row.status) > -1) {
    return false
  } else {
    return true
  }
}

// 列表-操作按钮
const butttondata = (row) => {
  return [
    defaultButtons.mainListEditBtn({
      hide: isShowMainButton(row, ['0']),
      hasPermi: 'qms:Q2:update'
    }), // 编辑
    defaultButtons.mainListDeleteBtn({
      hide: isShowMainButton(row, ['0']),
      hasPermi: 'qms:Q2:delete'
    }), // 删除
    defaultButtons.mainListFinishBtn({
      hide: isShowMainButton(row, ['0']),
      hasPermi: 'qms:Q2:finish'
    }) // 完成
  ]
}

// 列表-操作按钮事件
const buttonTableClick = async (val, row) => {
  if (val == 'edit') {
    // 编辑
    openForm('update', row)
  } else if (val == 'delete') {
    // 删除
    handleDelete(row.id)
  } else if (val == 'finish') {
    // 删除
    handleFinish(row.id)
  }
}

const handleFinish = async (id: number) => {
  try {
    await Q2Api.finishQ2(id)
    message.success(t('common.updateSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 添加/修改操作 */
const basicFormRef = ref()
const openForm = (type: string, row?: any) => {
  basicFormRef.value.open(type, row)
  if (type == 'create') {
    nextTick(() => {
      basicFormRef.value.formRef.setValues({
        handleTime: new Date().getTime(),
        claimTime: new Date().getTime(),
        priority: '3',
        disbursementAmount: 0
      })
    })
  }
}

// form表单提交
const formsSuccess = async (formType, data) => {
  data.responUser = userStore.getUser.id
  var isHave = Q2.allSchemas.formSchema.some(function (item) {
    return item.field === 'activeTime' || item.field === 'expireTime'
  })
  if (isHave) {
    if (data.activeTime && data.expireTime && data.activeTime >= data.expireTime) {
      message.error('失效时间要大于生效时间')
      return
    }
  }
  if (data.lightQty == 0) {
    message.error('数量不能为0')
    return
  }
  if (data.activeTime == 0) data.activeTime = null
  if (data.expireTime == 0) data.expireTime = null

  try {
    basicFormRef.value.formLoading = true
    if (formType === 'create') {
      await Q2Api.createQ2(data)
      message.success(t('common.createSuccess'))
    } else {
      await Q2Api.updateQ2(data)
      message.success(t('common.updateSuccess'))
    }
    basicFormRef.value.dialogVisible = false
    basicFormRef.value.formLoading = false
    getList()
  } finally {
    basicFormRef.value.formLoading = false
  }
}

/** 详情操作 */
const detailRef = ref()
const openDetail = (row: any, titleName: any, titleValue: any) => {
  detailRef.value.openDetail(row, titleName, titleValue, 'basicQ2')
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await Q2Api.deleteQ2(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const exportLoading = ref(false) // 导出的加载中
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    loadStart()
    const excelTitle = ref(route.meta.title)
    const data = await Q2Api.exportQ2(tableObject.params)
    download.excel(data, `【${excelTitle.value}】【${formatDate(new Date())}】.xlsx`)
  } catch {
  } finally {
    loadDone()
  }
}

/** 导入 */
const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}
// 导入附件弹窗所需的参数
const importTemplateData = reactive({
  templateUrl: '',
  templateTitle: `【${route.meta.title}】导入模版.xlsx`
})
// 导入成功之后
const importSuccess = () => {
  getList()
}

// 筛选提交
const searchFormClick = (searchData) => {
  tableObject.params = {
    isSearch: true,
    filters: searchData.filters
  }
  getList() // 刷新当前列表
}

/** 初始化 **/
onMounted(async () => {
  getList()
  importTemplateData.templateUrl = await Q2Api.importTemplate()
})
</script>
