<script setup lang="ts">
import { ref , watch, reactive, shallowReactive } from "vue"
import { useRenderIcon } from "/@/components/ReIcon/src/hooks";
import { BusinessQuery, PlatformQuery, CustomerQuery, AreaQuery } from "/@/components/BasicForm";
import { rules, biddingTypes, initialData, initialBidGoodData } from "./../config/_options"
import { httpDetail as httpProjectDetail } from "/@/api/sellOut/project";
import ActivityProductModal from "./activityProductModal.vue"
import ProjectModal from "./projectModal/index.vue"
import { useCompany } from "/@/hooks/core/useCompany";
import { ElForm, ElMessage } from "element-plus"
import { useTask } from "/@/hooks/core"


const { currentCompany } = useCompany()

const visible = shallowReactive({ project: false, activity: false })

const areaInfo = shallowReactive({ freedom: '', name: '' })
const formRef = ref<InstanceType<typeof ElForm> | null>(null) 
const areaQueryRef = ref<InstanceType<typeof AreaQuery> | null>(null)
const customerQueryRef = ref<InstanceType<typeof CustomerQuery> | null>(null)
const platformQueryRef = ref<InstanceType<typeof PlatformQuery> | null>(null)

const data = ref({ ...initialData })
const selection = ref([])

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 })
}})

const ladderTemp = reactive({ detail: {}, index: -1 })

async function submit(){
  try{
    formRef.value && formRef.value.validate()
    const { ladder } = data.value

  }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
}


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
}

function handleFreedomChange(){
  areaInfo.name = ''
}

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 }
)
</script>

<template>
  <div style="width:100%">
    <ElForm 
      label-width="100px" 
      :rules="rules" 
      ref="formRef"
      :model="data"
    >
      <ElRow :gutter="10">
        <ElCol :span="6">
          <ElFormItem label="竞价类型" prop="is_project">
            <ElSelect 
              v-model="data.is_project" 
              placeholder="竞价类型" 
              @change="handleIsProjectChange"
              style="width: 100%">
              <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'" 
              />
          </ElFormItem>
        </ElCol>
        <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'"
                @change="handleCustomerChange"
             />
          </ElFormItem>
        </ElCol>

        <ElCol :span="24">
          <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>        
        </ElCol>

        <template v-if="data.is_project === '1'">
          <ElCol :span="24">
            <ElFormItem label="项目信息">
              <ElAlert
                @click="() => visible.project = true"
                class="cursor-pointer select-none" 
                title="点击此处选择项目" 
                type="warning" 
                show-icon 
                center 
              />
            </ElFormItem>
          </ElCol>
            
          <ElCol :span="24">
              <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="70px"  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> 
            </ElCol>
        </template>

        <ElCol :span="24">
          <ElFormItem label="竞价商品要求" prop="ladder" label-width="100px">
            <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_id_name" />
              <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 
                label="商品名称" 
                prop="good_name" 
                minWidth="170" 
              />

              <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_name + sii">
                  <span v-if="sii !== 0">-</span>
                    {{ si.spec_name }}:[{{ si.spec_value_name}}]
                  </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>                
              </ElTableColumn>
            </ElTable>
          </ElFormItem>
        </ElCol>

        <ElCol :span="24">
          <div class="flex justify-end">
            <ElButton type="primary" @click="submit">保存</ElButton>
          </div>
        </ElCol>
      </ElRow>
    </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>
