<script setup lang="ts">
import { ref , watch, reactive, shallowReactive, nextTick, computed  } from "vue"
import { useRenderIcon } from "/@/components/ReIcon/src/hooks";
import { isMultiplePlaceOptions, isCustomizedOptions, bidRules } from "./../config/_options"
import { BusinessQuery, PlatformQuery, CustomerQuery, AreaQuery } from "/@/components/BasicForm";
import { rules, biddingTypes, createInitialData, initialBidGoodData } from "./../config/_options"
import { CategoryFlattenQuery, BrandQuey, UnitQuery } from "/@/components/BasicForm"
import { UnitInput } from "/@/components/Input";
import { httpDetail as httpProjectDetail } from "/@/api/sellOut/project";
import ActivityProductModal from "./activityProductModal.vue"
import ProjectModal from "./projectModal/index.vue"
import SpecForm from "/@/components/SpecForm"
import { useCompany } from "/@/hooks/core/useCompany";
import { ElForm, ElMessage } from "element-plus"
import { httpCreate, httpDetail, httpUpdate } from "/@/api/sellOut/zixunOrder";
import { ImageSingleUpload } from "/@/components/ImageUpload";
import { useRouter } from "vue-router"
import { useTask } from "/@/hooks/core"


const props = defineProps<{ isDetail: boolean, isCopy: boolean, isUpdate: boolean ,id: string }>()
const emit = defineEmits(['getDetail'])


const router = useRouter()
const { currentCompany } = useCompany()


const total = computed(() => {
  const { budget_price, num } = ( data.value.ladder[0] || {})
  return Number(budget_price * num).toFixed(2)
})

const areaInfo = shallowReactive({ freedom: '', name: '' })
  
const formRef = ref<InstanceType<typeof ElForm> | null>(null)
const visible = shallowReactive({ project: false, activity: false })
const areaQueryRef = ref<InstanceType<typeof AreaQuery> | null>(null)
const customerQueryRef = ref<InstanceType<typeof CustomerQuery> | null>(null)
const categoryFlattenQueryRef = ref<InstanceType<typeof CategoryFlattenQuery> | null>(null)


const selection = ref([])
const data = ref({ ...createInitialData() })
const ladderTemp = reactive({ detail: {}, index: -1 })

const createTask = useTask({ success(){ router.push('/sellOut/zixunOrder') }})

const updateTask = useTask({ success(){ router.push('/sellOut/zixunOrder') }})


const detailTask = useTask({ success: async(_data) => {
  const { 
      endtime, 
      is_project, 
      platform_code, 
      companyNo, 
      khName, 
      khNo, 
      area, 
      arrival_time, 
      is_addrs, 
      budget_price, 
      num, 
      is_custom,
      total_weight,
      unit,
      brand_id,
      cat_id,
      good_name,
      cost_desc,
      use_desc,
      remark,
      specinfo: _specinfo,
      good_img,
      enclosure_file, 
      metal_id,
      other_config,
      is_gold_price,
      specs_weight,
      config,
      can = []
  } = _data

  const { name: cat_name } = (can[2] || {}) 

  const specinfo = []

  _specinfo.forEach(item => {  
    specinfo.push({ ...item, spec_label: item.spec_name, spec_value_label: item.spec_value_name, spec_id: item.specid  }) 
  })


  data.value = { 
    endtime, 
    is_project, 
    platform_code, 
    companyNo,
    khNo,
    ladder: [
      { 
        budget_price,
        arrival_time, 
        is_addrs,
        num,
        is_custom,
        total_weight,
        unit,
        brand_id,
        cat_id,
        good_name,
        cost_desc,
        use_desc,
        remark,
        specinfo,
        good_img,
        file_url: enclosure_file,
        metal_id,
        other_config,
        is_gold_price,
        specs_weight,
        config 
      }
    ]
  }

  if(area === '无限制' || area === '不限区域'){
    areaInfo.freedom = '0'
    areaInfo.name = '0'
    data.value.area = ' '
  }else{
    areaInfo.freedom = ''
    areaInfo.name = area
    data.value.area = await areaQueryRef.value?.getRecurrentValue({ name: areaInfo.name })
  }


  data.value.khNo = await customerQueryRef.value?.getRecurrentValue({ companyName: khName })
  emit('getDetail', _data)

  nextTick(async () => {
    const result = await categoryFlattenQueryRef.value?.getRecurrentValue({ cat_name })
    data.value.ladder[0].cat_id = result
  })
}})


const projectDemandTask = useTask({ 
 initialData: {}, 
 success: async (response: any) => {
  const { khName, platform_code } = response
  data.value.platform_code = platform_code
  data.value.khNo = await customerQueryRef.value?.getRecurrentValue({ companyName: khName })
}})


async function submit(){
  if(data.value.ladder.length === 0){
    ElMessage.warning('至少提供一条商品要求！')
    return
  }

  try{
    formRef.value && formRef.value.validate()
    const {
      khNo,
      ladder,
      endtime,
      companyNo
    } = data.value

    if(new Date(endtime).getTime() <= new Date().getTime()){
      ElMessage.warning('竞价截止时间应该大于当前时间')
      return
    }

    const model: Record<string, any> = JSON.parse(JSON.stringify(data.value))
    model.companyNo = currentCompany.value.companyNo
    
    if(areaInfo.freedom === '0'){
      model.area = '不限区域'
    } else{
      model.area = areaInfo.name
    }

    model.ladder = []
    ladder.forEach(item => {
      const { 
        specs,
        specinfo: _specinfo,
        file_url: enclosure_file,
        isNoble: _1, 
        cat_name: _2,
        ...rest 
      } = item;

      const specinfo = [];
      (specs || _specinfo).forEach(item => { specinfo.push({ specid: item.spec_id, spec_value_id: item.spec_value_id }) });
      model.ladder.push({ ...rest, enclosure_file ,specinfo })
    })

    if(props.isUpdate){
      const { ladder = [], ...rest } = model
      updateTask.run(httpUpdate({ infoNo: props.id, ...ladder[0], ...rest }))
    } else {
      createTask.run(httpCreate(model))
    }
  }catch(err){
    console.log(err)
  }
}

function handleAddActivityProduct(){
  if(data.value.is_project === '1'){
    if(selection.value.length === 0){
      ElMessage.warning( "必须选择一个项目商品要求！")
      return
    }
    if(selection.value.length > 1){
      ElMessage.warning( "每次创建只能选择一个项目商品要求！")
      return
    }
    const { addtime: arrival_time, budget_price, good_name ,num } = selection.value[0]
    ladderTemp.detail = { ...initialBidGoodData, arrival_time, budget_price, good_name, num }
  }else {
    ladderTemp.detail = { ...initialBidGoodData }
  }
  visible.activity = true
  ladderTemp.index = -1
}

function handleUpdateLadder(index: number){
  ladderTemp.index = index
  ladderTemp.detail = {... data.value.ladder[index]}
  visible.activity = true
}

const disabledDate = (time: any) =>  time.getTime() < Date.now() - 60 * 60 * 24 * 1000;
const requestProjectDemands = (projectNo: string) => projectDemandTask.run(httpProjectDetail({ projectNo }))

/** 购买方改变时查找客户的收货地址并复制 */ 
async function handleCustomerChange({ area } = ({} as any)){
  if(area === '无限制' || area === '不限区域'){
    areaInfo.freedom = '0'
    areaInfo.name = '0'
    data.value.area = ' '
  }else{
    areaInfo.freedom = ''
    areaInfo.name = area
    data.value.area = await areaQueryRef.value?.getRecurrentValue({ name: areaInfo.name })
  }
}

/**  禁止选择项目单 */ 
function handleIsProjectChange(isProject: string){
  if(isProject != '1') return
  data.value.is_project = ''
  ElMessage.warning('项目咨询单不支持使用')
}

function handleAreaChange(row){
  areaInfo.freedom = ''
  areaInfo.name = row.search_name
  data.value.area = row.search_name
}

function handleFreedomChange(){
  areaInfo.name = '不限区域'
  data.value.area = '不限区域'
}


const isNoble = ref(false)
function handleCategoryChange(row){
  isNoble.value = !!row.is_gold
}

watch(() => data.value.is_project, () => {
  data.value.platform_code = ""
  data.value.khNo = ""
  selection.value = []
}, {
  immediate: true
})


watch(() => currentCompany, () => {
    if(!currentCompany) return
    data.value.companyNo = currentCompany.value.companyNo
  }, 
  { immediate: true, deep: true }
)

if(props.id){ detailTask.run(httpDetail({ infoNo: props.id })) }
</script>

<template>
  <div style="width:100%" v-loading="createTask.loading || detailTask.loading || updateTask.loading">
    <ElForm 
      label-width="100px" 
      :rules="rules" 
      ref="formRef"
      :model="data"
      :disabled="isDetail"
    >
      <ElRow :gutter="10">
        <ElCol :span="6">
          <ElFormItem label="竞价类型" prop="is_project">
            <ElSelect
              v-model="data.is_project" 
              placeholder="竞价类型" 
              @change="handleIsProjectChange"
              style="width: 100%"
              :disabled="isCopy || isUpdate">
              <ElOption 
                v-for="opt in biddingTypes" 
                :value="opt.value" 
                :label="opt.label"
                :key="opt.value" 
              />
            </ElSelect>
          </ElFormItem>
        </ElCol>

        <ElCol :span="6">
          <ElFormItem label="竞价截止时间" prop="endtime" label-width="120px">
            <ElDatePicker 
              v-model="data.endtime"
              :disabledDate="disabledDate"
              value-format="YYYY-MM-DD HH:mm:ss" 
              type="datetime" 
              style="width:100%" 
              placeholder="竞价截止时间"
            />
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem label="所属平台" prop="platform_code">
             <PlatformQuery
                ref="platformQueryRef" 
                v-model="data.platform_code" 
                placeholder="所属平台" 
                :disabled="data.is_project === '1' || isUpdate" 
              />
          </ElFormItem>
        </ElCol>
      </ElRow>

      <ElRow>
        <ElCol :span="12">
          <ElFormItem label="销售方" prop="companyNo">
            <BusinessQuery v-model="data.companyNo" disabled />
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem label="购买方" prop="khNo">
             <CustomerQuery 
                ref="customerQueryRef"
                v-model="data.khNo"  
                placeholder="购买方"
                :disabled="data.is_project === '1' || isUpdate"
                @change="handleCustomerChange"
             />
          </ElFormItem>
        </ElCol>
      </ElRow>
        
       <ElFormItem label="收货区域" prop="area">
         <div class="flex w-full">
           <ElRadio 
             v-model="areaInfo.freedom" 
             :disabled="!data.khNo || data.is_project === '1'" 
             @change="handleFreedomChange"
             label="0">
           不限</ElRadio>

           <AreaQuery 
             ref="areaQueryRef"  
             v-model="data.area" 
             :disabled="!data.khNo || data.is_project === '1'" 
             style="width: 100%" 
             @change="handleAreaChange" 
           />
         </div>  
       </ElFormItem>

        <template v-if="data.is_project === '1'">
            <ElFormItem label="项目信息">
              <ElAlert
                @click="() => visible.project = true"
                class="cursor-pointer select-none" 
                title="点击此处选择项目" 
                type="warning" 
                show-icon 
                center 
                :closable="false"
              />
            </ElFormItem>
            
            <ElFormItem label="项目商品要求" label-width="100px">
                <ElTable 
                  :data="projectDemandTask.data.ladder || []" 
                  @selection-change="value => selection = value"
                  v-loading="projectDemandTask.loading"
                  size="small" 
                  border 
                >
                  <ElTableColumn width="40px" type="selection" />
                  <ElTableColumn label="商品阶梯" width="70px"  show-overflow-tooltip>
                    <template #="{ $index }">{{ $index }}</template>
                  </ElTableColumn>
                  <ElTableColumn label="商品类型" width="79px"  show-overflow-tooltip>
                    <template #="{ row }">
                      <ElTag>{{ Number(row.good_type) === 1 ? '竞品' : Number(row.good_type) === 2  ? '竞聘' : '--'}}</ElTag>
                    </template>
                  </ElTableColumn>
                  <ElTableColumn label="预算单价" prop="budget_price" width="100px"  show-overflow-tooltip/>
                  <ElTableColumn label="购买数量" prop="num" width="100px"  show-overflow-tooltip />
                  <ElTableColumn label="商品分类" min-width="300px"  show-overflow-tooltip>
                    <template #="{ row }">
                      {{ row.cat_info.map(({name}) => name).join('-') }}
                    </template>
                  </ElTableColumn>
                  <ElTableColumn label="图片" width="80px">
                    <template #="{ row }">
                      <ElImage v-if="row.good_img" style="width:20px;height:20px" :src="row.good_img" :preview-src-list="[row.good_name]" />
                    </template>
                  </ElTableColumn>
                  <ElTableColumn label="商品名称" prop="good_name" min-width="180px" show-overflow-tooltip />
                </ElTable>
            </ElFormItem> 
        </template>

        <ElRow v-if="!isDetail && !isCopy && !isUpdate">
          <ElFormItem label="竞价商品要求" prop="ladder" label-width="120px">
            <ElTable border size="small" :data="data.ladder">
              <ElTableColumn label="商品阶梯">
                <template #="{ $index }">{{ $index + 1 }}</template>
              </ElTableColumn>
              <ElTableColumn label="预算单价" prop="budget_price" />
              <ElTableColumn label="购买数量" prop="num" />
              <ElTableColumn label="商品分类" prop="cat_name" min-width="300px" show-overflow-tooltip />
              <ElTableColumn label="图片">
                <template #="{ row }">
                  <ElImage 
                    v-if="row.good_img" 
                    :src="row.good_img" 
                    style="width:20px;height:20px" 
                    :preview-src-list="[row.good_img]" 
                  />
                </template>
              </ElTableColumn>

              <ElTableColumn
                prop="good_name"
                label="商品名称"
                show-overflow-tooltip
                min-width="170"
              />
            <ElTableColumn
              prop="specinfo"
              label="商品规格"
              show-overflow-tooltip
              width="170"
            >
              <template #="{ row }">
                <span v-for="(si, sii) in row.specs" :key="si.spec_label + sii">
                  <span v-if="sii !== 0">-</span>
                  {{ si.spec_label }}:[{{ si.spec_value_label}}]
                </span>
              </template>
            </ElTableColumn>

            <ElTableColumn
              prop="is_addrs"
              label="是否多地"
              width="70"
              show-overflow-tooltip
            >
              <template #="{ row }">
                {{ row.is_addrs === "1" ? "多地" : "一地" }}
              </template>
            </ElTableColumn>

            <ElTableColumn
              prop="is_custom"
              label="是否定制"
              width="70"
              show-overflow-tooltip
            >
              <template #="{ row }">
                {{ row.is_custom === "1" ? "定制" : "非定制" }}
              </template>
            </ElTableColumn>

              <ElTableColumn label="操作" fixed="right">
                <template #header>
                  <div class="flex w-full justify-between">
                    <p>操作</p>
                    <ElTooltip content="添加活动商品" placement="top">
                      <ElButton 
                        link 
                        size="small" 
                        type="primary" 
                        :icon="useRenderIcon('add')" 
                        @click="handleAddActivityProduct"
                      />
                    </ElTooltip>
                  </div>
                </template>


                <template #="{ $index }">
                  <ElTooltip content="编辑" placement="top">
                    <ElButton
                      @click="handleUpdateLadder($index)"
                      :icon="useRenderIcon('edits')" 
                      type="primary" 
                      link 
                    />
                  </ElTooltip>

                  <ElTooltip content="删除" placement="top">
                    <ElButton
                      @click="data.ladder.splice($index, 1)"
                      :icon="useRenderIcon('delete')" 
                      type="danger" 
                      link 
                    />
                  </ElTooltip>
                </template>
              </ElTableColumn>
            </ElTable>
          </ElFormItem>
        </ElRow>

        <template v-else>
          <ElRow v-if="data.ladder.length > 0">
            <ElCol :span="6">
              <ElFormItem label="到货日期">
                <ElDatePicker 
                  style="width:100%"
                  v-model="data.ladder[0].arrival_time"
                  :disabledDate="disabledDate"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="到货日期" 
                />
              </ElFormItem>
            </ElCol>

            <ElCol :span="6">
              <ElFormItem label="是否多地" prop="is_addrs">
                 <ElSelect style="width: 100%" placeholder="是否多地" v-model="data.ladder[0].is_addrs">
                    <ElOption 
                      v-for="opt in isMultiplePlaceOptions" 
                      :label="opt.label"
                      :value="opt.value"
                      :key="opt.value"
                    />
                 </ElSelect>
              </ElFormItem>
            </ElCol>

            <ElCol :span="6">
              <ElFormItem label="预算单价" prop="budget_price">
                <div class="flex">
                  <ElInputNumber 
                    v-model="data.ladder[0].budget_price"
                    controls-position="right"
                    placeholder="预算单价"  
                    style="width:100%" 
                    :precision="2"
                  />
                  <span class="ml-[5px]">元</span>
                </div>
              </ElFormItem>
            </ElCol>

            <ElCol :span="6">
              <ElFormItem label="数量" prop="num">
                <ElInputNumber
                 v-model="data.ladder[0].num"
                  style="width: 100%" 
                  controls-position="right" 
                  placeholder="数量"
                />
              </ElFormItem>
            </ElCol>

            <ElCol :span="6">
              <ElFormItem label="是否定制" prop="is_custom">
                <ElSelect style="width: 100%" placeholder="是否定制" v-model="data.ladder[0].is_custom">
                  <ElOption 
                    v-for="opt in isCustomizedOptions"
                    :label="opt.label"
                    :value="opt.value"
                    :key="opt.value"
                  />
                </ElSelect>
              </ElFormItem>
            </ElCol>

            <ElCol :span="6">
              <ElFormItem label="重量" prop="total_weight">
                <div class="flex">
                  <ElInputNumber 
                    style="width:100%"  
                    controls-position="right" 
                    :precision="3" 
                    v-model="data.ladder[0].total_weight" 
                  />
                  <span class="ml-[5px]">g</span>
                </div>
              </ElFormItem>
            </ElCol>

            <ElCol :span="6" >
              <ElFormItem label="单位" prop="unit">
                <UnitQuery v-model="data.ladder[0].unit" />
              </ElFormItem>
            </ElCol>

            <ElCol :span="6">
              <ElFormItem label="品牌" prop="brand_id">
                <BrandQuey v-model="data.ladder[0].brand_id" />
              </ElFormItem>
            </ElCol>

            <ElCol :span="12">
              <ElFormItem label="商品分类" prop="cat_id">
                <CategoryFlattenQuery
                  ref="categoryFlattenQueryRef"
                  :disabled="isUpdate"
                  v-model="data.ladder[0].cat_id" 
                  :companyNo="currentCompany.companyNo"
                  @change="handleCategoryChange"
                />
              </ElFormItem>
            </ElCol>

            <ElCol :span="12">
              <ElFormItem 
                label="商品名称" 
                prop="good_name">
                <ElInput v-model="data.ladder[0].good_name"  placeholder='商品名称' />
              </ElFormItem>
              <!-- <SpecForm v-model:specs="data.specs" /> -->
            </ElCol>
          </ElRow>

          <ElRow :gutter="10" v-if="data.ladder.length > 0">
            <ElCol :span="12">
              <ElFormItem label="工艺说明" prop="cost_desc">
                <ElInput v-model="data.ladder[0].cost_desc" placeholder="工艺说明" />
              </ElFormItem>
              
              <ElFormItem label="产品用途" prop="use_desc">
                <ElInput v-model="data.ladder[0].use_desc" placeholder="产品用途" />
              </ElFormItem>

              <ElFormItem label="产品备注" prop="remark">
                <ElInput v-model="data.ladder[0].remark" placeholder="产品用途" />
              </ElFormItem>
            </ElCol>      
            
            <ElCol :span="12">
              <SpecForm v-model:specs="data.ladder[0].specinfo" />
            </ElCol>
          </ElRow>

          <!-- 贵金属 -->
          <ElRow v-if="data.ladder.length > 0 && isNoble">
            <ElCol :span="12">
              <ElFormItem label="配置要求" prop="config">
                <ElSelect placeholder="配置要求" v-model="data.ladder[0].config" style="width: 100%">
                  <ElOption 
                    v-for="(item, index) in configOptions"
                    :key="item + index"
                    :label="item"
                    :value="item"
                  />
                </ElSelect>
              </ElFormItem>
            </ElCol>
          
            <ElCol :span="6">
              <ElFormItem label="金属克重" prop="specs_weight">
                <UnitInput unit="g" v-model="data.ladder[0].specs_weight" />
              </ElFormItem>
            </ElCol>
          
            <ElCol :span="6">
              <ElFormItem label="启用金价" prop="is_gold_price">
                <ElSelect v-model="data.ladder[0].is_gold_price"  style="width: 100%">
                  <ElOption 
                    v-for="item in isGoldPriceOptions"
                    :value="item.value"
                    :label="item.label"
                  />
                </ElSelect>
              </ElFormItem>
            </ElCol>
          </ElRow>

          <ElRow v-if="data.ladder.length > 0 && isNoble">
            <ElCol :span="16">
              <ElFormItem label="其他配置要求" prop="other_config" label-width="110px">
                <ElInput
                  v-model="data.ladder[0].other_config"
                  type="textarea" 
                  placeholder="其他配置要求"
                  maxlength="250"
                  show-word-limit
                  :rows="2"
                />
              </ElFormItem>
            </ElCol>
          
            <ElCol :span="8">

              <!-- -->
              <ElFormItem label="金属种类" prop="metal_id">
                <ElSelect placeholder="贵金属种类" style="width: 100%" v-model="data.ladder[0].metal_id">
                  <ElOption 
                    v-for="opt in nobleOptions" 
                    :value="opt.value" 
                    :label="opt.label" 
                  />
                </ElSelect>
              </ElFormItem>
            </ElCol>
          </ElRow>

          <ElRow v-if="data.ladder.length > 0">
            <ElCol :span="8">
              <ElFormItem label="商品图片" prop="good_img">
                <div class="flex justify-start">
                  <ImageSingleUpload v-model="data.ladder[0].good_img" />
                  <p class="ml-[10px]">小于1Mb</p>
                </div>
              </ElFormItem>
            </ElCol>


            <ElCol :span="8">
              <ElFormItem label="附件" prop="file_url">
                <UploadFile 
                  v-model="data.ladder[0].file_url" 
                />
              </ElFormItem>
            </ElCol>

            <ElCol :span="8">
              <div class="w-full flex flex-col items-end justify-center">
                <h3 class="text-right font-bold mb-[5px]">竞价单总额: {{ total }}</h3>
                <ElButton type="primary" @click="submit">保 存</ElButton>
              </div>
            </ElCol>
          </ElRow>
        </template>

        <ElCol :span="24" v-if="!isDetail && !isCopy && !isUpdate">
          <div class="flex justify-end">
            <ElButton type="primary" @click="submit">保 存</ElButton>
          </div>
        </ElCol>
      
    </ElForm>

    <ProjectModal 
      v-model:visible="visible.project"
      @confirm="requestProjectDemands"
    />

    <ActivityProductModal 
      v-model:visible="visible.activity"
      v-model:data="ladderTemp.detail"
      :index="ladderTemp.index"
      :isProject="data.is_project === '1'"
      @submit="({ newData, index }) => index === -1 ? data.ladder.push(newData) : data.ladder[index] = newData"
    />
  </div>
</template>
