<script setup lang="ts">
import { reactive, onMounted, ref } from "vue"

import { 
  Tabs, Tab, List, Image, showLoadingToast, closeToast, Button, showImagePreview, showFailToast, Dialog, Search, Field, showSuccessToast, showConfirmDialog,
  Loading
} from "vant"

import { requestSeeklist, requestSeekstatus, requestCompanyCategores, requestBusinessInfo, requestSupplierInfo } from "~/service/modules/home"
import axios from "axios"

const CancelToken = axios.CancelToken

const mapSpuCode = ref<string[]>([])
const selection = ref<Record<string, any>>([])

const state = reactive({
  skuOrName: '',
  isIndeterminate: false,
  isCheckAll: false,
  finished: false, 
  loading: false,
  approvalLoading: false,
  isInit: true,
  status: 0,
  total: 0,
  page: 0
})

const remark = ref('')
const visible = ref(false)
const approvalVisible = ref(false)

const currentItem = ref<any>({})

const list = ref<Record<string, any>[]>([])

const tabList = [
  { value: '0', label: '待审核', type: 'warning' },
  { value: '1', label: '审核通过', type: 'success' },
  { value: '2', label: '审核驳回', type: 'danger' },
  { value: '',  label: '全部'  }
]

let source:any = null;
async function onSearch(bidNo?: string, isReset?: boolean){
  // if( state.finished) return
  if(state.isInit || isReset){ showLoadingToast({ message: '加载中...', forbidClick: true }) }
  
  if(!bidNo){  state.page += 1 }

  if(isReset){
    list.value = []
    state.page = 1
  }

  state.loading = true
  source = CancelToken.source()

  const { code, data } = await requestSeeklist({ 
    tax_status: bidNo ? '' : state.status,
    page: bidNo ? 1 : state.page,
    skuOrName: state.skuOrName,
    info_status: ['2', '7'],
    bidNo: bidNo || '',
    platform_id: 76,
    is_combind: 0
  }, 
    source.token
  )
  state.loading = false
  if(code == 0){
    if(bidNo){
      const sourceIndex = list.value.findIndex(item => item.bidNo === bidNo)

      if(String(state.status) === ''){
        list.value[sourceIndex] = data.list[0]
      } else {
        list.value.splice(sourceIndex, 1)
      }

    } else {
      list.value = [...list.value, ...data.list]
      state.finished = data.list.length < 10;
    }
    state.total = data.count
  }

  if(state.isInit || isReset){
    closeToast()
    state.isInit = false
  }
}

function handleTabChange(){
  source && source.cancel()
  state.skuOrName = ''
  state.isCheckAll = false
  state.isIndeterminate = false
  mapSpuCode.value = []
  selection.value = []
  state.page = 0
  state.finished = false
  state.loading = false
  list.value = [];
  onSearch()
}

async function handleNoStatus(){
  if(remark.value.trim().length === 0){
    visible.value = true
    showFailToast('请输入驳回原因!')
    return
  }
  showLoadingToast({ message: '审核中...', forbidClick: true })
  const { code } = await requestSeekstatus({
    "status": '2',
    "out_tax": "",
    "out_tax_id": "",
    "goodCombind": [],
    "remark": remark.value,
    "bidNo": currentItem.value.bidNo
  })
  if(code == 0){
    showSuccessToast('审核成功')
    visible.value = false
    approvalVisible.value = false
    onSearch(currentItem.value.bidNo)
  }
}

async function handleSubmit(item = ({} as any)){
  // showLoadingToast({ message: '加载中...', forbidClick: true })
  try{
    state.approvalLoading = true
  
    currentItem.value.isOk = true
    currentItem.value.isLegalerOk = true

    approvalVisible.value = true; 
    currentItem.value = item;
    
    const company = await requestBusinessInfo({ companyNo: item.companyNo })
    const supplier = await requestSupplierInfo({ code: item.supplierNo })
    
    if((company.data || {}).legaler_type != (supplier.data || {}).legaler_type){
      currentItem.value.isLegalerOk = false
      currentItem.value.isOk = true
      state.approvalLoading = false
      return
    }else {
      currentItem.value.isLegalerOk = true
    }

    const { in_info } = item;
    if(in_info.merge_code){
    const result = await requestCompanyCategores({ companyNo: item.companyNo, output_status: '1', cat_code: in_info.merge_code })
    if(result.code == 0){
      if(result.data.list.length === 0){
        currentItem.value.isOk = false
      } else {
        const { merge_code } = result.data.list[0]
        if(merge_code !== in_info.merge_code){
          currentItem.value.isOk = false
        } else {
          currentItem.value.isOk = true
        }
      }
    }else {
      currentItem.value.isOk = false
    }
    } else {
      currentItem.value.isOk = false
    }

    state.approvalLoading = false
  }catch(err){
    state.approvalLoading = false
  }
}


function handleApprovalResult(){
  visible.value = true
  remark.value = ''
}

function handleClose(){
  currentItem.value.isOk = true
  currentItem.value.isLegalerOk = true
}

function handleOkStatus(){
  showConfirmDialog({ title: '提示', message: '是否确认通过?' })
  .then(async () => {
    showLoadingToast({ message: '审核中...', forbidClick: true })
    const { code } = await requestSeekstatus({
      "status": '1',
      "out_tax": currentItem.value.tax + '%',
      "out_tax_id": currentItem.value.in_info.id,
      "remark": '',
      "bidNo": currentItem.value.bidNo,
      "goodCombind": []
    })

    if(code == 0){
      console.log('joined')
      showSuccessToast('审核成功')
      approvalVisible.value = false
      visible.value = false
      onSearch(currentItem.value.bidNo)
    }
  })
}

const isApproval = (item) => item.tax_status == '0'
</script>

<template>
  <div class="bg-[#f5f5f5] w-full" style="height:calc(100vh - 50px);overflow: auto">
    <Tabs style="z-index:1000" class="w-full fixed top-0 left-0" v-model:active="state.status" @change="handleTabChange">
      <Tab v-for="tab in tabList" :title="tab.label" :key="tab.value" :name="tab.value" />
    </Tabs>

    <div 
      class="w-full flex bg-[#fff] fixed top-[43px] left-0 items-center" 
      style="z-index:1000; border-bottom: 1px solid #f5f5f5" 
    >
      <Search 
        class="flex-1"
        v-model="state.skuOrName"
        placeholder="SKU编号/商品名称" 
        @clear="onSearch('', true)"
      />
      
      <Button 
        class="mr-[15px] ml-[-10px]" 
        type="warning"
        size="small"
        @click="onSearch('', true)"
      >搜索</Button>
    </div>
    
    <List class="mt-[95px] w-full" v-model:loading="state.loading" :finished="state.finished" finished-text="没有更多了" @load="onSearch">
       <div :show="true" class="bg-[#fff] my-[3px] border-[#f5f5f5]" v-for="item in list" :key="item.id">
        <div class="p-[15px] flex items-start">
          <div class="float-right items-start w-full">
           <div class="flex flex-col ml-[10px]" style="line-height:22px">
             <div class="color-[#0f0f0f] flex items-start">
                <Image 
                  style="
                    height:28px;
                    width:28px;
                    min-height:28px;
                    min-width:28px;
                    margin-right: 10px;
                    border-radius: 2px;
                    border: 1px solid #dcdfe6;
                    overflow:hidden
                  " 
                  @click="showImagePreview([item.good_img])"
                  :src="item.good_img"
                />
                <p class="font-[16px] font-700 py-[5px]">{{ item.good_name }}</p>
             </div>
             
            <div class="flex flex-col color-[#34495e] font-500" style="font-size: 13px">
              <div class="flex">
                <p  class="w-[65px] text-right pr-[5px]">审核状态:</p>
                <p>{{ tabList.find(({ value }) => item.tax_status == value)?.label || '--' }}</p>
              </div>

              <div class="flex">
                <p class="w-[65px]  text-right pr-[5px]">SKU编号:</p>
                <p>{{ item.spuCode }}</p>
              </div>

              <template v-if="item.tax_status != 1">
                <div class="flex">
                  <p class="w-[65px]  text-right pr-[5px]">类目编码:</p>
                  <p>{{ item.in_info.merge_code }}</p>
                </div>

                <div class="flex">
                  <p  class="w-[65px]  text-right pr-[5px]">类目名称:</p>
                  <p>{{ item.in_info.cat_name }}</p>
                </div>
              </template>


              <template v-else>
                <div class="flex">
                  <p class="w-[65px]  text-right pr-[5px]">类目编码:</p>
                  <p>{{ item.out_info.merge_code }}</p>
                </div>

                <div class="flex">
                  <p  class="w-[65px]  text-right pr-[5px]">类目名称:</p>
                  <p>{{ item.out_info.cat_name }}</p>
                </div>

                <div class="flex">
                  <p  class="w-[65px]  text-right pr-[5px]">销项税率:</p>
                  <p>{{ item.out_tax }}%</p>
                </div>
              </template>


              <div class="flex">
                <p  class="w-[65px] text-right pr-[5px]">工艺材质:</p>
                <p>{{ item.cost_desc }}</p>
              </div>

              <div v-if="isApproval(item)">
                <p  class="w-[65px] text-right pr-[5px]" style="white-space: nowrap;line-height: 25px">审核结果: </p>
                <div class="flex ml-[10px] float-right mt-[-25px]" >
                  <Button
                    round
                    class="mr-[10px] px-[15px] h-[25px]"
                    type="warning" 
                    plain  
                    @click="visible = true; currentItem = item"
                    size="small"
                  >审核不通过</Button>
                   <!-- @click="handleOkStatus" -->
                  <Button
                    class="px-[15px] h-[25px]"
                    round
                    type="warning"
                    size="small"
                    @click="handleSubmit(item)"
                  >提交审核结果</Button>
                </div>
              </div>
             </div>
           </div>
         </div>
        </div>
       </div>
    </List>

    <Dialog v-model:show="visible" title="驳回原因" @close="remark = ''">
      <Field
        v-model="remark"
        placeholder="驳回原因"
        type="textarea"
        rows="3" 
      />

      <template #footer>
        <div class="flex">
          <Button 
            class="flex-1" 
            @click="visible = false; remark = ''"
            style="border-radius: 0px"
          >取消</Button>
          
          
          <Button 
            class="flex-1" 
            type="warning" 
            @click="handleNoStatus" 
            style="border-radius: 0px"
          >提交</Button>
        </div>
      </template>
    </Dialog>

    <Dialog 
      v-model:show="approvalVisible" 
      title="提交审核结果"
      :closeOnClickOverlay="true"
      @close="handleClose"
    >


    <div class="w-full flex justify-center my-[10px]" v-if="state.approvalLoading">
      <Loading size="24px" color="#ed6a0c" vertical>加载中...</Loading>
    </div>

      <div  v-else class="flex flex-col ml-[10px] p-[10px]" style="line-height:22px">
         <div class="color-[#0f0f0f] flex items-start">
            <Image 
              style="height:28px;width:28px;min-height:28px;min-width:28px;margin-right: 10px;border-radius:2px;border:1px solid #dcdfe6;overflow:hidden" 
              @click="showImagePreview([currentItem.good_img])"
              :src="currentItem.good_img"
            />

            <p class="font-[16px] font-700 py-[5px]">{{ currentItem.good_name }}</p>
         </div>
         
        <div class="flex flex-col color-[#34495e] font-500" style="font-size: 13px">
          <div class="flex">
            <p  class="w-[85px] text-right pr-[5px]">审核状态:</p>
            <p>{{ tabList.find(({ value }) => currentItem.tax_status == value)?.label || '--' }}</p>
          </div>

          <div class="flex">
            <p class="w-[85px]  text-right pr-[5px]">SKU编号:</p>
            <p>{{ currentItem.spuCode }}</p>
          </div>

          <div class="flex">
            <p  class="w-[85px]  text-right pr-[5px]">{{ currentItem.isOk && currentItem.isLegalerOk ? '类目编码:' : '预计类目编码:' }}</p>
            <p>{{ currentItem.in_info.merge_code }}</p>
          </div>

          <div class="flex">
            <p  class="w-[85px]  text-right pr-[5px]">{{ currentItem.isOk && currentItem.isLegalerOk ? '类目名称:' : '预计类目名称:' }}</p>
            <p>{{ currentItem.in_info.cat_name }}</p>
          </div>

          <div class="flex">
            <p  class="w-[85px]  text-right pr-[5px]">{{ currentItem.isOk && currentItem.isLegalerOk ? '进项税率:' : '预计进项税率:' }}</p>
            <p>{{ currentItem.tax }}%</p>
          </div>

          <div class="flex">
            <p  class="w-[85px]  text-right pr-[5px]">工艺材质:</p>
            <p>{{ currentItem.cost_desc }}</p>
          </div>

          <p 
            class="text-center w-full my-[10px] color-red" 
            v-if="!currentItem.isOk"
          >当前业务公司销项没有该类目,请驳回</p>

          <p 
            class="text-center w-full my-[10px] color-red" 
            v-if="!currentItem.isLegalerOk"
          >供应商资质不一致,请驳回</p>
         </div>

         
       </div>

       <template #footer>
          <div class="flex" v-if="!state.approvalLoading">
            <Button
              class="flex-1" 
              @click="handleApprovalResult"
              style="border-radius: 0px"
            >驳回</Button>
            
            <Button 
              v-if="currentItem.isOk && currentItem.isLegalerOk"
              style="border-radius: 0px"
              @click="handleOkStatus"
              class="flex-1" 
              type="warning" 
            >通过</Button>
          </div>
       </template>
    </Dialog>
  </div>
</template>
