<template>
  <div class="workflowTradeDetail container-height">
    <Breadcrumb />
    <div class="flex-column-center">
      <div class="font_size30 bold">{{t('workflowTradeAdd.publishDemand')}}</div>
      <div class="gray font_size20">{{t('workflowTradeAdd.publishDemandTip')}}</div>
    </div>
    <div class="flex-between mt10">
      <div class="flex_1 mr20">
        <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-position="top" class="page-add">
          <!-- 基本信息 -->
          <div class="padding16 bg_color_fff border_radius_10 box_shadow_card">
            <div class="gap10">
              <div class="line_vertical"></div>
              <div class="font_size20 bold">{{t('workflowTradeAdd.basicInfo')}}</div>
            </div>
            <div class="mt10">
              <el-form-item label="" prop="title">
                <div>
                  <span class="color_required font_size16">*</span>
                  <span class="font_size16 bold">{{t('workflowTradeAdd.demandTitle')}}</span>
                  <span class="font_size14 gray999 ml20">{{t('workflowTradeAdd.demandTitleTip')}}</span>
                </div>
                <el-input v-model="ruleForm.title" :placeholder="t('workflowTradeAdd.placeholderDemandTitle')"  maxlength="50" show-word-limit/>
              </el-form-item>
              <el-form-item label="" prop="categoryId3">
                <div>
                  <span class="color_required font_size16">*</span>
                  <span class="font_size16 bold">{{t('workflowTradeAdd.workflowType')}}</span>
                  <span class="font_size14 gray999 ml20">{{t('workflowTradeAdd.workflowTypeTip')}}</span>
                </div>
                <!-- 树形选择 -->
                <el-cascader 
                  v-model="categoryIdList"
                  :options="categoryListTree"
                  :placeholder="t('workflowTradeAdd.placeholderWorkflowType')"
                  style="width:100%"
                  :props="{
                    label: 'categoryName',
                    value: 'categoryId',
                    children: 'children',
                  }"
                />
              </el-form-item>
            </div>
          </div>
          <!-- 详细内容 -->
          <div class="padding16 bg_color_fff border_radius_10 mt10 box_shadow_card">
            <div class="gap10">
              <div class="line_vertical"></div>
              <div class="font_size20 bold">{{t('workflowTradeAdd.detailInfo')}}</div>
            </div>
            <div class="mt10">
              <el-form-item :label="$t('workflowTradeAdd.background')" prop="background">
                <el-input v-model="ruleForm.background" :placeholder="t('workflowTradeAdd.placeholderBackground')"  maxlength="500" type="textarea" show-word-limit rows="7"/>
              </el-form-item>
              <el-form-item :label="$t('workflowTradeAdd.requirements')" prop="requirements">
                <el-input v-model="ruleForm.requirements" 
                rows="7"
                :placeholder="t('workflowTradeAdd.requirementsTip')
+t('workflowTradeAdd.requirementsTip1')
                "  maxlength="2000" type="textarea" show-word-limit/>
              </el-form-item>
            </div>
          </div>
          <!-- 项目信息 -->
          <div class="padding16 bg_color_fff border_radius_10 mt10 box_shadow_card">
            <div class="gap10">
              <div class="line_vertical"></div>
              <div class="font_size20 bold">{{$t('workflowTradeAdd.projectInfo')}}</div>
            </div>
            <div class="mt10">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="" prop="budgetMin">
                    <div>
                      <span class="font_size16 bold">{{$t('workflowTradeAdd.budgetLowerLimit')}}({{$t('common.RMB')}})</span>
                      <span class="font_size14 gray999 ml20">{{$t('workflowTradeAdd.budgetLowerLimitTip')}}</span>
                    </div>
                    <el-input v-model="ruleForm.budgetMin" :placeholder="$t('workflowTradeAdd.placeholderBudgetLowerLimit')"  maxlength="11" type="number" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="" prop="budgetMax">
                    <div>
                      <span class="font_size16 bold">{{$t('workflowTradeAdd.budgetUpperLimit')}}({{$t('common.RMB')}})</span>
                      <span class="font_size14 gray999 ml20">{{$t('workflowTradeAdd.budgetLowerLimitTip')}}</span>
                    </div>
                    <el-input v-model="ruleForm.budgetMax" :placeholder="$t('workflowTradeAdd.placeholderBudgetUpperLimit')"  maxlength="11" type="number" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item :label="$t('common.signUpDeadline')" prop="deadline">
                <!-- 只能选择之后的时间 -->
                <el-date-picker
                  v-model="ruleForm.deadline"
                  type="date"
                  value-format="YYYY-MM-DD"
                  :placeholder="$t('workflowTradeAdd.selectSignUpDeadline')"
                  :disabled-date="time => time.getTime() < Date.now() - 8.64e7"
                />
              </el-form-item>
            </div>
          </div>
          <!-- 联系方式 -->
          <div class="padding16 bg_color_fff border_radius_10 mt10 box_shadow_card">
            <div class="gap10">
              <div class="line_vertical"></div>
              <div class="font_size20 bold">{{$t('workflowTradeAdd.contactInfo')}}</div>
            </div>  
            <div class="mt10">
              <el-form-item :label="$t('workflowTradeAdd.phoneNumber')" prop="phone">
                <el-input v-model="ruleForm.phone" :placeholder="$t('workflowTradeAdd.placeholderPhoneNumber')"  maxlength="11"/>
              </el-form-item>
              <el-form-item :label="$t('workflowTradeAdd.wechat')" prop="wechat">
                <el-input v-model="ruleForm.wechat" :placeholder="$t('workflowTradeAdd.placeholderWechat')"  maxlength="50"/>
              </el-form-item>
              <el-form-item :label="$t('workflowTradeAdd.email')" prop="email">
                <el-input v-model="ruleForm.email" :placeholder="$t('workflowTradeAdd.placeholderEmail')"  maxlength="50"/>
              </el-form-item>
            </div>
          </div>
          <div class="mt20">
            <el-button type="primary" class="font_size16 gradient" 
             :loading="isSubmiting"
            @click="submitForm" size="large">
              <el-icon><Promotion /></el-icon>
              <span class="ml10">{{$t('common.fabuxuqiu')}}</span>
            </el-button>
            <el-button class="font_size16" @click="goBack"  size="large">
              <el-icon><Close /></el-icon>
              <span class="ml10">{{$t('common.cancel')}}</span>
            </el-button>
          </div>
        </el-form>
      </div>
      <!-- 发布提示 -->
      <div class="detail_right">
        <div class="detail_right_content detail_right">
          <div class="padding16 bg_color_fff border_radius_16 box_shadow_card">
            <div class="gap10">
              <div class="line_vertical"></div>
              <div class="font_size20 bold">{{$t('workflowTradeAdd.publishTip')}}</div>
            </div>
            <!-- 无序列表 -->
            <div class="font_size16 ql-container">
              <div class="ql-editor">
                <div v-html="release_hint"></div>
              </div>
              <!-- <div>· 标题要简洁明了，突出核心需求</div>
              <div>· 详细描述需求背景和具体要求</div>
              <div>· 明确交付标准和验收方式</div>
              <div>· 合理设置预算范围</div>
              <div>· 添加相关标签提高匹配度</div> -->
            </div>
          </div>
          <div class="padding16 bg_color_fff border_radius_16 mt20 box_shadow_card">
            <div class="gap10">
              <div class="line_vertical"></div>
              <div class="font_size20 bold">{{$t('workflowTradeAdd.publishRules')}}</div>
            </div>
            <!-- 有序列表 -->
            <div class="font_size16 editor ql-container ">
              <div class="ql-editor">
                <div v-html="release_rules"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import riliIcon from '@/assets/imgs/rili.png'
import biaoqianIcon from '@/assets/imgs/biaoqian.png'
import yuangong from '@/assets/imgs/yuangong.png'
import zaixianbaomingIcon from '@/assets/imgs/zaixianbaoming.png'
import dianhuaIcon from '@/assets/imgs/dianhua.png'
import weixinIcon from '@/assets/imgs/weixin.png'
import youxiangIcon from '@/assets/imgs/youxiang.png'
import DGTMessage from '@/utils/message'

import { questAdd, getQuestDetail, questEdit } from '@/api/workflowTrade.js'
import { getCategoryListTree } from '@/api/category.js'
import { getAgreementType } from '@/api/common.js'

import { useI18n } from 'vue-i18n' 
const { t } = useI18n()
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()
console.log(router,route)
import { ref, computed, reactive, onMounted, watchEffect,nextTick } from 'vue'
import { useAppStore } from '@/pinia/appStore'
const appStore = useAppStore()
// 防止重复提交的加载状态
const isSubmiting = ref(false)
//获取参数
const query = route.query;
const questId = ref(query.id || '')
// 分类列表树
const categoryListTree = ref([]);
// 选择的分类id列表
const categoryIdList = ref([])

// 表单实例
const ruleFormRef = ref(null)
const ruleForm = reactive({
  questId: "",
  title: '',
  categoryId1: '',
  categoryId2: '',
  categoryId3: '',
  background: '',
  requirements: '',
  budgetMin: '',
  budgetMax: '',
  deadline: '',
  phone: '',
  wechat: '',
  email: '',
})
watchEffect(() => {
  // 将选择的分类id列表赋值给表单的categoryId1、categoryId2、categoryId3
  ruleForm.categoryId1 = categoryIdList.value[0] || ''
  ruleForm.categoryId2 = categoryIdList.value[1] || ''
  ruleForm.categoryId3 = categoryIdList.value[2] || ''
})
// 校验规则
const rules = reactive({
  title: [
    { required: true, message: t('workflowTradeAdd.placeholderDemandTitle'), trigger: 'blur' },
  ],
  categoryId3: [
    { required: true, message: t('workflowTradeAdd.placeholderWorkflowType'), trigger: 'blur' },
  ],
  background: [
    { required: true, message: t('workflowTradeAdd.placeholderBackground'), trigger: 'blur' },
  ],
  requirements: [
    { required: true, message: t('workflowTradeAdd.placeholderRequirements'), trigger: 'blur' },
  ],
  budgetMin: [
    // { required: true, message: '请输入预算下限', trigger: 'blur' },
    { validator: (rule, value, callback) => /^\d+(\.\d{1,2})?$/.test(value), message: t('workflowTradeAdd.pleaseInputRightBudgetLowerLimit'), trigger: 'blur' },
  ],
  budgetMax: [
    // { required: true, message: '请输入预算上限', trigger: 'blur' },
    { validator: (rule, value, callback) => /^\d+(\.\d{1,2})?$/.test(value), message: t('workflowTradeAdd.pleaseInputRightBudgetUpperLimit'), trigger: 'blur' },
  ],
  deadline: [
    { required: true, message: t('workflowTradeAdd.selectSignUpDeadline'), trigger: 'change' },
  ],
  phone: [
    { required: true, message: t('workflowTradeAdd.placeholderPhoneNumber'), trigger: 'blur' },
    { validator: (rule, value, callback) => /^1[3456789]\d{9}$/.test(value), message: t('common.pleaseInputRightPhoneNumber'), trigger: 'blur' },
  ],
  email: [
    { required: true, message: t('workflowTradeAdd.placeholderEmail'), trigger: 'blur' },
    { validator: (rule, value, callback) => /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/.test(value), message: t('common.pleaseInputRightEmail'), trigger: 'blur' },
  ],
});

onMounted(() => {
  // 查询分类信息（返回树状结构）
  getCategoryListTreeFn();
  // 查询发布提示和发布规则
  getAgreementTypeFn();
  if(questId.value){
    getDetail();
  }

})

// 提交表单
const submitForm = async () => {
  await ruleFormRef.value.validate(async(valid, fields,name) => {
    console.log(valid, fields,name)
    if (!valid) {
      //报错第一个key
      let firstKey = Object.keys(fields)[0]
      DGTMessage.warning(fields[firstKey][0].message)
      return
    }
    let req = questAdd;
    if(questId.value){
      req = questEdit;
    }
    // 设置加载状态为true，禁用按钮
    isSubmiting.value = true
    // 新增需求工作流
    await req(ruleForm).then(res => {
      console.log(res)
      if(res.code === 200){
        DGTMessage.success(t('workflowTrade.publishSuccess'))
        goBack();
      }
    }).finally(() => {
      // 提交完成后，将加载状态设置为false，启用按钮
      setTimeout(() => {
        isSubmiting.value = false
      }, 1000)
    })
    
  })
};
const goBack = () => {
  router.back()
};
const getCategoryListTreeFn = () => {
  getCategoryListTree().then(res => {
    console.log(res)
    categoryListTree.value = res.rows || [];
  })
};
const getDetail = () => {
  getQuestDetail({id:questId.value}).then(res => {
    const detail = res.data || {};
    for(let key in ruleForm){
      ruleForm[key] = detail[key];
    }
    nextTick(() => {
      if(ruleForm.categoryId1){
        categoryIdList.value = [ruleForm.categoryId1, ruleForm.categoryId2, ruleForm.categoryId3];
      };
    });
    console.log(categoryIdList.value)
  })
};

// 发布提示列表
const release_hint = ref([])
// 发布规则列表
const release_rules = ref([])
const getAgreementTypeFn = () => {
  getAgreementType({agreementType: 'release_hint'}).then(res => {
    console.log(res)
    release_hint.value = res.data.content || '';
  })
  getAgreementType({agreementType: 'release_rules'}).then(res => {
    console.log(res)
    release_rules.value = res.data.content || '';
  })
};

</script>

<style scoped lang="scss">
  .workflowTradeDetail{
    
  }

</style>
