<script setup lang="ts">
import { ref, computed, watch } from "vue"
import { httpInvoiceDetail } from "/@/api/invoice"
import { useTask } from "/@/hooks/core"
import { ElForm, ElMessage, ElMessageBox } from "element-plus" 

import RemarkModal from "./remark-modal.vue" 

import { useRenderIcon } from "/@/components/ReIcon/src/hooks";


const emit = defineEmits(['submit'])
const props = withDefaults(defineProps<{
  code: string;
  successCode?: string;
  rejectCode?: string;
  mode?: 'sale' | 'purchase';
  readonly: boolean
}>(),
{ mode: 'purchase', rejectCode: '0', successCode: '1' });

const formRef = ref<InstanceType<typeof ElForm> | null>(null)

const rules = computed(() => ({
  status: [{ required: true, message: '请选择审核状态', trigger: 'change' }],
  remark: [{ required: formData.value.status == props.rejectCode, message: '请输入备注', trigger: 'change' }],
}))


const orders = ref([])

const pagination = ref({
  currentPage: [],
  size: 10,
  page: 1
})

// const currentPage = ref([])

const formData = ref({ status: props.successCode, remark: '' })


const stat = computed(() => 
orders.value.reduce((prev, current) => {
     const isUnState = current.cat_diff == '2' || current.tax_diff == '2'
     let unState = prev.unState
     let unRemark = prev.unRemark
     if(isUnState){
      unState += 1
      if(!current.remark) { unRemark += 1 }
    }
    return { unState, unRemark }
  }, {
    unRemark: 0,
    unState: 0
 })
)

// 发票明细相关处理
const invoiceDetailTask  = useTask<any>({ initialData: [], success(data = []) {
  const list = []
  const map:Map<string, string> = new Map()
  data.forEach(({ OrderInfo = [], good_name, total_amount }) => {
    OrderInfo.forEach(item => {
      const { diff_info = {}, code = '' } = item
      const { tax_diff, cat_diff } = diff_info
      const symbol = `${code}-${tax_diff}-${cat_diff}`
      list.push({ ...item, itemGoodName: good_name , itemTotalAmount: total_amount ,remark: item.remark || '' })
    })
  })


  list.forEach(item => {
    if(Object.keys(item.diff_info).length !== 0) formData.value.status = props.rejectCode
  })

  orders.value = list
  pagination.value.page = 1
  const { page, size } = pagination.value
  pagination.value.currentPage = orders.value.slice((page - 1) * size,  page * size)
}})

const refreshInvoiceDetail = () => invoiceDetailTask.run(httpInvoiceDetail({ code: props.code  }))

// async function onSubmit(){
//   try{
//     await formRef.value.validate()
//     let isOk = true
//     const ItemRemark = orders.value.map(item => {
//       if((item.cat_diff == '2' || item.tax_diff == '2')  && !item.remark){ isOk = false }
//       return { id: item.id, remark: item.remark }
//     }) 

//     if(!isOk && formData.value.status != props.rejectCode){
//       ElMessage.warning('税率或类目不一致时,订单备注不能为空。')
//       return
//     }

//     emit('submit', { ...formData.value,  ItemRemark})
//   }catch(err){
//     console.log(err)
//   }
// }


const remarkState = ref({
  data: '',
  index: -1,
  visible: false
})

function handleRemark(data: object, index: number){
  remarkState.value.data = data.remark
  remarkState.value.index = index
  remarkState.value.visible = true
}


function handleAddRemark(remark, index){
  const { page, size } = pagination.value
  const newIndex = ((page - 1) * size ) + index
  orders.value[newIndex].remark = remark
  const { unRemark, unState } = orders.value.reduce((prev, current) => {
     const isUnState = current.cat_diff == '2' || current.tax_diff == '2'
     let unState = prev.unState
     let unRemark = prev.unRemark
     if(isUnState){
      unState += 1
      if(!current.remark) { unRemark += 1 }
    }
    return { unState, unRemark }
  }, {
    unRemark: 0,
    unState: 0
 })


 if(unRemark === 0){
  const ItemRemark = orders.value.map(item => ({ id: item.id, remark: item.remark })) 
  emit('submit', { ...formData.value, status: '3', ItemRemark })
 }
}

async function handleStatusChange(){
  if(formData.value.status != props.successCode){
    if(!formData.value.remark){
      ElMessage.warning('审核备注不能为空')
      return
    }

    ElMessageBox.confirm('驳回后所有备注将被清除,是否确认?','提示', { type: 'warning' })
    .then(() => {
      const ItemRemark = orders.value.map(item => ({ id: item.id, remark: item.remark })) 
      emit('submit', { ...formData.value, ItemRemark })
    })
  }else{
    if(Number(stat.value.unRemark) !== 0){
      ElMessage.warning('请填写所有异常数据的备注')
      return
    }
    const ItemRemark = orders.value.map(item => ({ id: item.id, remark: item.remark }))
    emit('submit', { ...formData.value, ItemRemark })
  }
}


function handleCurrentChange(value){
  const { page, size } = pagination.value
  console.log(page)
  pagination.value.currentPage = orders.value.slice((page - 1) * size, page * size)
}

watch(() => props.code, () => {
  if(!props.code) return
  refreshInvoiceDetail()
},{
  immediate: true
})
</script>

<template>
  <div class="flex flex-col">
    <div class="mb-[10px] flex justify-between items-center" v-if="!readonly">
      <p>共 {{orders.length}} 条数据, 异常: {{ stat.unState }} 条, 未添加备注: {{ stat.unRemark }} 条</p>
    
    
      <div class="flex items-center">
        <span style="color:red;margin-right: 5px">*</span>
        <p class="mr-[5px]" style="text-wrap:nowrap">审核结果:</p>
        <ElSelect class="mr-[5px]" v-model="formData.status" style="width:100%" placeholder="审核结果" :disabled="stat.unState !== 0">
          <ElOption :value="successCode" label="通过" />
          <ElOption :value="rejectCode" label="驳回" />
        </ElSelect>


        <span style="color:red;margin-right: 5px" v-if="formData.status !== successCode">*</span>
        <p class="mr-[5px]" style="text-wrap:nowrap">审核备注:</p>
        <ElInput 
          class="mr-[5px]" 
          v-model="formData.remark" 
          placeholder="审核备注" 
        />

        <ElButton :type="formData.status === successCode ? 'success' : 'danger'" @click="handleStatusChange">
          {{ formData.status === successCode ? '确认通过' : '确认驳回' }}
        </ElButton>
      </div>
    </div>

      <ElTable border size="small" :data="pagination.currentPage">
        <ElTableColumn width="60px" label="序号" type="index" />

        <ElTableColumn label="发票明细信息">
        <ElTableColumn label="货物或应税劳务、服务名称" width="170px" prop="itemGoodName" show-overflow-tooltip>
          <template #="{ row }">
            <el-popover
              placement="top-start"
              :width="150"
              trigger="hover"
              :content="'发票明细ID:' + row.itemId"
            >
              <template #reference>
                  <el-button
                    link
                    :icon="useRenderIcon('information-line')"
                  />
              </template>
            </el-popover>
          {{ row.itemGoodName }}
        </template>

        </ElTableColumn>

        <ElTableColumn label="税后金额" prop="total_amount"  width="100px" show-overflow-tooltip>
          <template #="{ row }">
            {{ row.itemTotalAmount }}
          </template>
        </ElTableColumn>
      </ElTableColumn>


      <ElTableColumn label="关联金额" prop="total_amount">
        <template #="{ row }">
          {{ row.total_amount - row.balance_amount }}
        </template>
      </ElTableColumn>

      <ElTableColumn label="订单编号" min-width="160px" prop="code" show-overflow-tooltip />
      
      
      <ElTableColumn label="商品名称" min-width="160px" prop="good_name" show-overflow-tooltip>
        <template #="{ row }">
          <el-popover
              placement="top-start"
              :width="270"
              trigger="hover"
              :content="'商品编号:' + row.spuCode"
            >
              <template #reference>
                  <el-button
                    link
                    :icon="useRenderIcon('information-line')"
                  />
              </template>
        </el-popover>
        {{ row.good_name }}
        </template>
      </ElTableColumn>

    
      
      
      <ElTableColumn label="类目编号">
        <ElTableColumn label="预计" min-width="120px" show-overflow-tooltip>
          <template #="{ row }">
            <template v-if=" row.cat_diff == '2'">
              {{ row.diff_info?.cat_code.order_cat_code }}
            </template>

            <template v-else>
              {{ row.cat_code }}
            </template> 
        </template>
        </ElTableColumn>

        <ElTableColumn label="实开" min-width="120px" show-overflow-tooltip>
          <template #="{ row }">
            <template v-if=" row.cat_diff == '2'">
              {{ row.diff_info?.cat_code.inv_cat_code }}
            </template>

            <template v-else>
              {{ row.cat_code }}
            </template> 
          </template>
        </ElTableColumn>

        <ElTableColumn label="状态" width="70px" show-overflow-tooltip>
          <template #="{ row }">
            <ElTag size="small" :type="row.cat_diff == '2' ? 'danger' : 'success'">{{ row.cat_diff == '2' ? '不一致' : '一致' }}</ElTag>
          </template>
        </ElTableColumn>
      </ElTableColumn>


      <ElTableColumn label="类目税率">
        <ElTableColumn label="预计" width="60px" show-overflow-tooltip>
          <template #="{ row }">
            <!-- {{ row.diff_info?.tax.order_tax }} -->
            <template v-if=" row.tax_diff == '2'">
              {{ row.diff_info?.tax.order_tax }}
            </template>

            <template v-else>
              {{ row.tax }}%
            </template> 
          </template>
        </ElTableColumn>

        
      
        <ElTableColumn label="实开" width="60px" show-overflow-tooltip>
          <template #="{ row }">
            <!-- {{ row.diff_info?.tax.inv_tax }} -->
            <template v-if=" row.tax_diff == '2'">
              {{ row.diff_info?.tax.inv_tax }}
            </template>

            <template v-else>
              {{ row.tax }}%
            </template> 
          </template>
        </ElTableColumn>

        <ElTableColumn label="状态" min-width="70x" show-overflow-tooltip>
          <template #="{ row }">
            <ElTag size="small" :type="row.tax_diff == '2' ? 'danger' : 'success'">{{ row.tax_diff == '2' ? '不一致' : '一致' }}</ElTag>
          </template>
        </ElTableColumn>
      </ElTableColumn>



      <ElTableColumn label="备注" prop="remark" width="180px" />

      <ElTableColumn label="操作" width="60px" fixed="right" v-if="!readonly">
        <template #="{ row, $index }">
          <ElTooltip content="修改备注" placement="top">
            <ElButton type="primary" link size="small" :icon="useRenderIcon('edit')" @click="handleRemark(row, $index)"></ElButton>
          </ElTooltip>
        </template>
      </ElTableColumn>
    </ElTable>


    <div class="w-full flex justify-end">
      <ElPagination 
        class="mt-[10px]" 
        layout="prev, pager, next"  
        background
        v-model:currentPage="pagination.page"
        @current-change="handleCurrentChange"
        :size="pagination.size"
        :total="orders.length"  
      />
    </div>

    <!-- <ElForm v-if="!readonly" ref="formRef" :model="formData" :rules="rules" class="mt-[10px]" label-width="80px" style="width:400px"> -->
      <!-- <ElFormItem label="审核结果" prop="status">
      
      </ElFormItem> -->
      <!-- <ElFormItem label="备注" prop="remark">
        <ElInput v-model="formData.remark" placeholder="备注" type="textarea" />
      </ElFormItem> -->
      <!-- <ElFormItem>
        <div style="width:100%;display:flex;justify-content: flex-end;">
          <ElButton type="primary" @click="onSubmit">保存</ElButton>
        </div>
      </ElFormItem> -->
    <!-- </ElForm> -->

    <RemarkModal 
      v-model:visible="remarkState.visible" 
      :index="remarkState.index" 
      :data="remarkState.data" 
      @confirm="handleAddRemark"
    />
  </div>
</template>
