<template>
  <div class="main-container">
    <el-card class="box-card !border-none" shadow="never" v-loading="loading">
      <div class="flex justify-between items-center">
        <span class="text-lg">{{ pageName }}</span>
        <el-text type="info" size="small">
          <el-icon><InfoFilled /></el-icon>
          阶段名称来自系统字典"sales_title"配置
        </el-text>
      </div>
    </el-card>

    <el-card class="box-card !border-none" shadow="never">
      <div class="flex items-center justify-between p-[10px] table-item-border bg">
        <span class="text-base w-[230px]">阶段名称</span>
        <span class="text-base w-[110px] text-center">底薪</span>
      </div>

      <el-collapse v-model="activeNames" accordion>
        <el-collapse-item v-for="(stage, index) in stages" :key="stage.id" :name="stage.id">
          <template #title>
            <div class="collapse-title">
              <span class="title-name">{{ stage.name }}</span>
              <span class="arrow">{{ stage.price }} 元</span>
              <!-- <span class="arrow">&gt;</span> -->
            </div>
          </template>

          <el-form label-width="100px" style="margin-bottom: 10px">
            <el-form-item label="阶段名称">
              <el-input v-model="stage.name" placeholder="阶段名称" readonly/>
            </el-form-item>
          </el-form>

          <el-form label-width="100px" style="margin-bottom: 10px">
            <el-form-item label="阶段底薪">
              <el-input v-model="stage.price" placeholder="请输入阶段底薪"/>
            </el-form-item>
          </el-form>

          <el-button type="success" size="small" @click="addRule(stage)">新增规则</el-button>

          <el-table :data="stage.rules" border style="margin-top: 10px">
            <el-table-column prop="renewal_standard_min" label="续费率上限">
              <template #default="{ row }">
                <el-input v-model="row.renewal_standard_min" placeholder="请输入续费率上限" :max="100" type="number">
                  <template #append>
                    <el-button type="primary">%</el-button>
                  </template>
                </el-input>
              </template>
            </el-table-column>

            <el-table-column prop="renewal_standard_max" label="续费率下限">
              <template #default="{ row }">
                <el-input v-model="row.renewal_standard_max" placeholder="请输入续费率下限" :max="100" type="number">
                  <template #append>
                    <el-button type="primary">%</el-button>
                  </template>
                </el-input>
              </template>
            </el-table-column>

            <el-table-column prop="renewal_commission" label="续费提成">
              <template #default="{ row }">
                <el-input v-model="row.renewal_commission" placeholder="输入续费提成金额" type="number">
                  <template #append>
                    <el-button type="primary">元</el-button>
                  </template>
                </el-input>
              </template>
            </el-table-column>

            <el-table-column prop="new_count_min" label="新单成交数上限">
              <template #default="{ row }">
                <el-input v-model="row.new_count_min" placeholder="输入完单数量" type="number">
                  <template #append>
                    <el-button type="primary">单</el-button>
                  </template>
                </el-input>
              </template>
            </el-table-column>

            <el-table-column prop="new_count_max" label="新单成交数下限">
              <template #default="{ row }">
                <el-input v-model="row.new_count_max" placeholder="输入完单数量" type="number">
                  <template #append>
                    <el-button type="primary">单</el-button>
                  </template>
                </el-input>
              </template>
            </el-table-column>


            <!--						<el-table-column prop="xf_count_min" label="续费成交数上限">-->
            <!--							<template #default="{ row }">-->
            <!--								<el-input v-model="row.xf_count_min" />-->
            <!--							</template>-->
            <!--						</el-table-column>-->

            <!--						<el-table-column prop="xf_count_max" label="续费成交数下限">-->
            <!--							<template #default="{ row }">-->
            <!--								<el-input v-model="row.xf_count_max" />-->
            <!--							</template>-->
            <!--						</el-table-column>-->

            <!--						<el-table-column prop="new_move_5" label="新招（5+1）x3">-->
            <!--							<template #default="{ row }">-->
            <!--								<el-input v-model="row.new_move_5" />-->
            <!--							</template>-->
            <!--						</el-table-column>-->
            <!--						<el-table-column prop="new_move_7" label="新招（7+1）x3">-->
            <!--							<template #default="{ row }">-->
            <!--								<el-input v-model="row.new_move_7" />-->
            <!--							</template>-->
            <!--						</el-table-column>-->
            <el-table-column label="操作" width="100">
              <template #default="{ $index }">
                <el-button type="danger" size="small" @click="removeRule(stage, $index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

        </el-collapse-item>
      </el-collapse>


      <el-form label-position="left" label-width="100px" class="config-form" style="margin-top: 70px;">


        <h2 style="margin-bottom: 20px">多人介入完单资源业绩配置比例</h2>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="一访成交">
              <el-input v-model="form.qt_firstVisit" placeholder="请输入一访成交时提成的分配比例" :max="100" type="number">
                <template #append>
                  <el-button type="primary">%</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="二访成交">
              <el-input v-model="form.qt_secondVisit" placeholder="请输入二访成交时提成的分配比例" :max="100" type="number">
                <template #append>
                  <el-button type="primary">%</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="追单">
              <el-input v-model="form.qt_followUp" placeholder="请输入追单成功的分配比例" :max="100" type="number">
                <template #append>
                  <el-button type="primary">%</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="内部员工">
              <el-input v-model="form.qt_internalStaff" placeholder="请输入资源为内部员工时的提成金额" type="number">
                <template #append>
                  <el-button type="primary">元</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <h2 style="margin-bottom: 20px">课程提成</h2>
        <view v-for="(item, index) in course_type">
          <el-form-item :label="item.name">
            <el-input v-model="item.num" placeholder="请输入金额" style="width: 200px;" type="number">
              <template #append>
                <el-button type="primary">元</el-button>
              </template>
            </el-input>
          </el-form-item>
        </view>

      </el-form>
      <div style="text-align: right; margin-top: 20px">
        <el-button type="primary" @click="onSave">提交保存</el-button>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import {xsyjConfig, getXsyjConfig} from '@/app/api/sys'
import {useDictionary} from '@/app/api/dict'
import {reactive, ref, onMounted} from 'vue'
import {ElMessage} from 'element-plus'
import {InfoFilled} from '@element-plus/icons-vue'
import {useRoute} from 'vue-router'

const route = useRoute()
const pageName = route.meta.title

const loading = ref(true)
const stages = ref([])
const activeNames = ref(null)
const salesTitleList = ref([])


const form = ref({
  qt_firstVisit: '',
  qt_secondVisit: '',
  qt_followUp: '',
  qt_internalStaff: '',
});

const course_type = ref({});

// 获取销售职称字典数据
const getSalesTitleList = async () => {
  try {
    const res = await useDictionary('sales_title')
    salesTitleList.value = res.data?.dictionary || []
  } catch (error) {
    console.error('获取销售职称失败:', error)
    salesTitleList.value = []
  }
}

// 根据字典数据初始化阶段
const initStagesFromDict = () => {
  if (salesTitleList.value.length === 0) return
  
  // 重新构建阶段数据，确保所有字典中的职称都有对应的阶段
  const newStages = []
  
  salesTitleList.value.forEach(title => {
    // 查找是否已有该职称的配置
    const existingStage = stages.value.find(stage => 
      stage.title_key === title.value || stage.name === title.name
    )
    
    if (existingStage) {
      // 更新现有阶段的名称和标识
      newStages.push({
        ...existingStage,
        id: title.value,
        title_key: title.value,
        name: title.name,
      })
    } else {
      // 创建新的阶段配置
      newStages.push({
        id: title.value,
        title_key: title.value,
        name: title.name,
        price: 0,
        rules: [
          {
            renewal_standard_min: '0',
            renewal_standard_max: '',
            renewal_commission: '',
            new_count_min: '0',
            new_count_max: '',
            xf_count_min: '0',
            xf_count_max: '',
            new_move_5: '',
            new_move_7: '',
          },
        ],
      })
    }
  })
  
  stages.value = newStages
}

// 不再需要删除阶段功能，阶段由字典控制

function addRule(stage) {
  stage.rules.push({
    renewal_standard_min: '0',
    renewal_standard_max: '',
    renewal_commission: '',
    new_count_min: '0',
    new_count_max: '',
    xf_count_min: '0',
    xf_count_max: '',
    new_move_5: '',
    new_move_7: '',
  })
}

function removeRule(stage, ruleIndex) {
  if (stage.rules.length === 1) {
    ElMessage.warning('至少保留一条规则')
    return
  }
  stage.rules.splice(ruleIndex, 1)
}

const setFormData = async () => {
  try {
    // 先获取销售职称字典数据
    await getSalesTitleList()
    
    // 获取现有配置数据
    const data = await (await getXsyjConfig()).data
    stages.value = data.data || []
    form.value = data.form || {}
    course_type.value = data.course_type || {}
    
    // 根据字典数据初始化或补充阶段
    initStagesFromDict()
    
    loading.value = false
  } catch (error) {
    console.error('获取配置数据失败:', error)
    loading.value = false
  }
}

// 页面加载时初始化数据
onMounted(() => {
  setFormData()
})

const onSave = async () => {
  xsyjConfig({'stages': stages.value, 'form': form.value, 'course_type': course_type.value})
      .then(() => {
        loading.value = true
        setFormData()
      })
      .catch(() => {
        loading.value = false
      })
}
</script>

<style lang="scss" scoped>
.collapse-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  font-size: 14px;
  font-weight: 500;
  padding-right: 10px;
  color: #333;
  padding: 10px;
}

.title-name {
  width: 230px;
}

.title-salary {
  width: 110px;
  text-align: center;
  color: #7438d5;
}

.arrow {
  margin-left: auto;
  color: #999;
  font-size: 14px;
}
</style>