<template>
    <el-card shadow="never" class="list-card">
        <!-- <template #header>
            <div class="search" v-show="showSearch">
                <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
                        <el-form-item  prop="blurry">
                            <el-input v-model="queryParams.blurry" placeholder="输入搜索" clearable style="width: 240px" @keyup.enter="handleQuery" />
                        </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </template> -->

        <Table ref="ruleConfigTable"
               :tableParams="tableParams"
               :rightBtn="[]"
               @handleEdit="handleUpdate"
               @selectionChange="handleSelectionChange"
        >
        </Table>
    </el-card>
    <!-- 设置规则配置 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="650px" append-to-body>
      <!-- 客户模块设置 -->
      <div class="rule_set" v-if="form.resourceType=='10'">
        <div class="set_section">
          <div class="flex-center set_switch">
            <div class="bold">是否限制成员拥有客户上限</div>
            <el-switch v-model="form.hasMaxMember" />
          </div>
          <div class="desc">设置后成员将无法创建或领取超限额客户</div>
          <div class="div_input" v-if="form.hasMaxMember">
            <el-input v-model="form.maxMemberNum" type='number' placeholder="请输入客户拥有最大数量" />
            <span class="div_unit">条</span>
          </div>
        </div>
        <div class="set_section">
          <div class="flex-center set_switch">
            <div class="bold">客户置公设置</div>
            <el-switch v-model="form.hasPublicClues" />
          </div>
          <div class="desc">设置后对超过限额时间未跟进的成员客户进行置公</div>
          <div class="div_input" v-if="form.hasPublicClues">
            <el-input v-model="form.maxPublicCluesNum" type='number' placeholder="请输入客户最大未跟进天数" />
            <span class="div_unit">天</span>
          </div>
        </div>
        <div class="set_section">
          <div class="flex-center set_switch">
            <div class="bold">是否区分重点客户与普通客户</div>
            <el-switch v-model="form.hasDistinguishKeyRegular" />
          </div>
          <div v-if="form.hasDistinguishKeyRegular">
            <div class="flex-center" style="justify-content: space-between;margin-bottom: 10px;">
              <div class="flex-center">
                <span>普通客户最大未跟进天数</span>
                <el-input v-model="form.regularFollowDate" type='number' placeholder="" class="little_input"/>
                <span class="div_unit">天</span>
              </div>
              <div class="flex-center">
                <span>普通客户最大未成交天数</span>
                <el-input v-model="form.regularTransactionDate" type='number' placeholder="" class="little_input"/>
                <span class="div_unit">天</span>
              </div>
            </div>
            <div class="flex-center" style="justify-content: space-between;">
              <div class="flex-center">
                <span>重点客户最大未跟进天数</span>
                <el-input v-model="form.keyFollowDate" type='number' placeholder="" class="little_input" />
                <span class="div_unit">天</span>
              </div>
              <div class="flex-center">
                <span>重点客户最大未成交天数</span>
                <el-input v-model="form.keyTransactionDate" type='number' placeholder="" class="little_input" />
                <span class="div_unit">天</span>
              </div>
            </div>
          </div>
        </div>
        <div class="set_section">
          <div class="flex-center set_switch">
            <div class="bold">是否区分客户类型</div>
            <el-switch v-model="form.hasDistinguishCustomerType" />
          </div>
          <div v-if="form.hasDistinguishCustomerType">
            <div class="flex-center" style="justify-content: space-between;margin-bottom: 10px;column-gap: 10px" v-for="(item, index) in form.customerTypeRules">
              <SelectDict style="width:120px" v-model="item.customerTypeDictValue" placeholder="客户类型" dictCode="customer_type"></SelectDict>
              <div class="flex-center">
                <span>最大未跟进天数</span>
                <el-input v-model="item.customerTypeFollowDate" type='number' placeholder="" class="little_input"/>
                <span class="div_unit">天</span>
              </div>
              <div class="flex-center">
                <span>最大未成交天数</span>
                <el-input v-model="item.customerTypeTransactionDate" type='number' placeholder="" class="little_input"/>
                <span class="div_unit">天</span>
              </div>
              <el-icon color="#000" class="rule_del" @click="delCustomerTypeRule(index)"><Minus /></el-icon>
            </div>
            <div class="flex-center" style="cursor: pointer;" @click='addCustomerTypeRules'><el-icon color="#1874FF"><Plus /></el-icon>添加</div>
          </div>
        </div>
        <div class="set_section">
          <div class="flex-center set_switch">
            <div class="bold">公海客户变更垃圾客户设置</div>
            <el-switch v-model="form.hasGarbageClues" />
          </div>
          <div class="desc">设置后对超过限额时间未跟进的公海客户变更至垃圾客户</div>
          <div class="div_input" v-if='form.hasGarbageClues'>
            <el-input v-model="form.maxGarbageCluesNum" type='number' placeholder="请输入公海客户最大未跟进天数" />
            <span class="div_unit">天</span>
          </div>
        </div>
        <div class="set_section">
          <div class="flex-center set_switch">
            <div class="bold">垃圾客户清空设置</div>
            <el-switch v-model="form.hasGarbageEmptyClues" />
          </div>
          <div class="desc">设置后对超过限额时间未跟进的垃圾客户进行清空</div>
          <div class="div_input" v-if='form.hasGarbageEmptyClues'>
            <el-input v-model="form.maxGarbageEmptyCluesNum" type='number' placeholder="请输入垃圾客户最大未跟进天数" />
            <span class="div_unit">天</span>
          </div>
        </div>
        <div class="set_section">
          <div class="flex-center set_switch">
            <div class="bold">查重规则配置</div>
            <el-switch v-model="form.hasPlagiarismRules" />
          </div>
          <div class="desc">当规则开启后，成员添加客户将进行查重</div>
          <div class="div_input" v-if='form.hasPlagiarismRules'>
            <div class="flex-center item" style="justify-content: space-between;" v-for="(item,index) in form.fieldSimilarityls">
              <el-select v-model="form.fieldSimilarityls[index].fieldCode" style="width: 170px;" @change="changeRuleField(index)">
                  <el-option v-for="item in ruleFieldData" :label="item.fieldName" :value="item.fieldCode"></el-option>
              </el-select>
              <el-input v-model="item.similarityValue" placeholder="请输入相似度" style="width: 170px;" :disabled="item.fieldCode=='customerCompany.email'||item.fieldCode=='liaison.email'" />
              <div class="flex-center">
                <span style="margin-right: 5px;">{{item.canSave?'仅提示，可添加':'冲突后无法添加'}}</span>
                <el-switch v-model="item.canSave" />
              </div>
              <el-icon color="#000" class="rule_del" @click="delPlagiarismRule(index)"><Minus /></el-icon>
            </div>
            <div class="flex-center add_btn" @click='addPlagiarismRules'><el-icon color="#1874FF"><Plus /></el-icon>添加查重字段</div>
          </div>
        </div>
        <div class="set_section">
          <div class="flex-center set_switch">
            <div class="bold">更新备注</div>
          </div>
          <el-input v-model="form.updateExplain" placeholder="请输入备注信息" type="textarea" maxlength="30" show-word-limit/>
        </div>
      </div>
      <!-- 线索模块设置 -->
      <div class="rule_set" v-if="form.resourceType=='11'">
        <div class="set_section">
          <div class="flex-center set_switch">
            <div class="bold">是否限制成员拥有线索上限</div>
            <el-switch v-model="form.hasMaxMember" />
          </div>
          <div class="desc">设置后成员将无法创建或领取超限额线索</div>
          <div class="div_input" v-if='form.hasMaxMember'>
            <el-input v-model="form.maxMemberNum" type='number' placeholder="请输入线索拥有最大数量" />
            <span class="div_unit">条</span>
          </div>
        </div>
        <div class="set_section">
          <div class="flex-center set_switch">
            <div class="bold">线索置公设置</div>
            <el-switch v-model="form.hasPublicClues" />
          </div>
          <div class="desc">设置后对超过限额时间未跟进的成员线索进行置公</div>
          <div class="div_input" v-if='form.hasPublicClues'>
            <el-input v-model="form.maxPublicCluesNum" type='number' placeholder="请输入线索最大未跟进天数" />
            <span class="div_unit">天</span>
          </div>
        </div>
        <div class="set_section">
          <div class="flex-center set_switch">
            <div class="bold">公共线索清空设置</div>
            <el-switch v-model="form.hasClearClues" />
          </div>
          <div class="desc">设置后对超过限额时间未跟进的公共线索进行清空</div>
          <div class="div_input" v-if='form.hasClearClues'>
            <el-input v-model="form.maxClearCluesNum" type='number' placeholder="请输入公共线索最大未跟进天数" />
            <span class="div_unit">天</span>
          </div>
        </div>
        <div class="set_section">
          <div class="flex-center set_switch">
            <div class="bold">查重规则配置</div>
            <el-switch v-model="form.hasPlagiarismRules" />
          </div>
          <div class="desc">当规则开启后，成员添加线索将进行查重</div>
          <div class="div_input" v-if='form.hasPlagiarismRules'>
            <div class="flex-center item" style="justify-content: space-between;" v-for="(item,index) in form.fieldSimilarityls">
              <el-select v-model="form.fieldSimilarityls[index].fieldCode" style="width: 170px;" @change="changeRuleField(index)">
                  <el-option v-for="item in ruleFieldData" :label="item.fieldName" :value="item.fieldCode"></el-option>
              </el-select>
              <el-input v-model="item.similarityValue" placeholder="请输入相似度" style="width: 170px;" :disabled="item.fieldCode=='customerCompany.email'||item.fieldCode=='liaison.email'" />
              <div class="flex-center">
                <span style="margin-right: 5px;">{{item.canSave?'仅提示，可添加':'冲突后无法添加'}}</span>
                <el-switch v-model="item.canSave" />
              </div>
              <el-icon color="#000" class="rule_del" @click="delPlagiarismRule(index)"><Minus /></el-icon>
            </div>
            <div class="flex-center add_btn" @click='addPlagiarismRules'><el-icon color="#1874FF"><Plus /></el-icon>添加查重字段</div>
          </div>
        </div>
        <div class="set_section">
          <div class="flex-center set_switch">
            <div class="bold">更新备注</div>
          </div>
          <el-input v-model="form.updateExplain" placeholder="请输入备注信息" type="textarea" maxlength="30" show-word-limit/>
        </div>
      </div>
      <!-- 联系人模块设置 -->
      <div class="rule_set" v-if="form.resourceType=='20'">
        <div class="set_section">
          <div class="flex-center set_switch">
            <div class="bold">查重规则配置</div>
            <el-switch v-model="form.hasPlagiarismRules" />
          </div>
          <div class="desc">当规则开启后，成员添加线索将进行查重</div>
          <div class="div_input" v-if='form.hasPlagiarismRules'>
            <div class="flex-center item" style="justify-content: space-between;" v-for="(item,index) in form.fieldSimilarityls">
              <el-select v-model="form.fieldSimilarityls[index].fieldCode" style="width: 170px;">
                  <el-option v-for="item in ruleFieldData" :label="item.fieldName" :value="item.fieldCode"></el-option>
              </el-select>
              <el-input v-model="item.similarityValue" placeholder="请输入相似度" style="width: 170px;" :disabled="item.fieldCode=='customerCompany.email'||item.fieldCode=='liaison.email'" />
              <div class="flex-center">
                <span style="margin-right: 5px;">{{item.canSave?'仅提示，可添加':'冲突后无法添加'}}</span>
                <el-switch v-model="item.canSave" />
              </div>
              <el-icon color="#000" class="rule_del" @click="delPlagiarismRule(index)"><Minus /></el-icon>
            </div>
            <div class="flex-center add_btn" @click='addPlagiarismRules'><el-icon color="#1874FF"><Plus /></el-icon>添加查重字段</div>
          </div>
        </div>
        <div class="set_section">
          <div class="flex-center set_switch">
            <div class="bold">更新备注</div>
          </div>
          <el-input v-model="form.updateExplain" placeholder="请输入备注信息" type="textarea" maxlength="30" show-word-limit/>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">提交</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
</template>

<script setup name="RuleConfig" lang="ts">
import { listRuleConfig, getRuleConfig, delRuleConfig, addRuleConfig,getRuleField } from '@/api/system/ruleConfig';
import { RuleConfigVO, RuleConfigQuery, RuleConfigForm } from '@/api/system/ruleConfig/types';
import auth from '@/plugins/auth'
import Table from '@/components/Table/index.vue'
import { tableTypes } from '@/components/Table/types'
import { useDictCache } from '@/hooks/web/useDict'

const { queryDictDetailByCodes } = useDictCache(['customer_type'])
queryDictDetailByCodes()

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const ruleConfigList = ref<RuleConfigVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
// const leftBtn = ref<Array<string | number>>(
//     []);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const ruleConfigFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});


const tableParams = reactive<tableTypes<RuleConfigQuery, RuleConfigVO>>({
    tableColumn: [
                {show: true, label: '模块', prop: 'resourceName', sortable: false},
                {show: true, label: '最后更新', prop: 'updateTime', sortable: false},
                {show: true, label: '更新人', prop: 'updateByName', sortable: false},
                {show: true, label: '更新说明', prop: 'updateExplain', sortable: false},
                {
                    show: true, label: '操作', width: 200, prop: 'operation', disabledMove: true, render: ({ column }: { column: RuleConfigVO }) => {
                        return [
                            h(ElButton, {link: true, type: 'primary',onClick:() => {handleUpdate(column)}}, '设置'),
                        ]
                    }
                },
    ],
    keyId: 'id',
    queryParams: {
      blurry: '',
    },
    listFn: listRuleConfig,
    delFn: delRuleConfig,
})


const initFormData: RuleConfigForm = {
  fieldSimilarityls:[{
    canSave: undefined,
    fieldCode: undefined,
    fieldName: undefined,
    similarityValue: undefined,
  }],
  hasClearClues: undefined,
  hasDistinguishKeyRegular: undefined,
  hasMaxMember: undefined,
  hasPlagiarismRules: undefined,
  hasPublicClues: undefined,
  keyFollowDate: undefined,
  keyTransactionDate: undefined,
  maxClearCluesNum: undefined,
  maxMemberNum: undefined,
  maxPublicCluesNum: undefined,
  plagiarismRules: undefined,
  regularFollowDate: undefined,
  regularTransactionDate: undefined,
  resourceType: undefined,
  updateExplain: undefined,
  hasGarbageClues: undefined,
  maxGarbageCluesNum: undefined,
  hasGarbageEmptyClues: undefined,
  maxGarbageEmptyCluesNum: undefined,
  customerTypeRules: [],
  hasDistinguishCustomerType: false,
}
const data = reactive<PageData<RuleConfigForm, RuleConfigQuery>>({
  form: {...initFormData},
  rules: {}
});

const {  form, rules } = toRefs(data);

const { queryParams } = toRefs(tableParams);
/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  ruleConfigFormRef.value?.resetFields();
}

const ruleConfigTable = ref()
/** 搜索按钮操作 */
const handleQuery = () => {
    ruleConfigTable.value.getData()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: RuleConfigVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

const ruleFieldData = ref([])
/** 修改按钮操作 */
const handleUpdate = async (row?: RuleConfigVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getRuleConfig({id: _id});
  Object.assign(form.value, res.result);
  const resourceType = row?.resourceType || ''
  const res2 = await getRuleField(resourceType);
  ruleFieldData.value = res2?.result;
  console.log(res.result)
  console.log(form.value)
  dialog.visible = true;
  dialog.title = "设置";
}

const changeRuleField = (index: number) => {
  form.value.fieldSimilarityls[index].fieldName = ruleFieldData.value.find(item => item.fieldCode == form.value.fieldSimilarityls[index].fieldCode).fieldName
}


const getList = () => {
    ruleConfigTable.value.getData()
}
/** 提交按钮 */
const submitForm = async() => {
  buttonLoading.value = true;
  await addRuleConfig(form.value).finally(() =>  buttonLoading.value = false);
  ElMessage.success('修改成功')
  dialog.visible = false;
  await getList();
}
// 修改设置
// 添加查重字段
const addPlagiarismRules = ()=>{
  form.value.fieldSimilarityls = form.value.fieldSimilarityls || []
  form.value.fieldSimilarityls.push({
    canSave: false,
    fieldCode: undefined,
    fieldName: undefined,
    similarityValue: undefined,
  })
}

//删除查重字段
const delPlagiarismRule=(index:number)=>{
  form.value.fieldSimilarityls.splice(index,1)
}

const addCustomerTypeRules = () => {
  form.value.customerTypeRules = form.value.customerTypeRules || []
  form.value.customerTypeRules.push({
    customerTypeDictValue: undefined,
    customerTypeFollowDate: undefined,
    customerTypeTransactionDate: undefined
  })
}

const delCustomerTypeRule = (index: number) => {
  form.value.customerTypeRules.splice(index, 1)
}


onMounted(() => {
});
</script>
<style lang="scss" scoped>
  .rule_set{
    .set_switch{
      justify-content: space-between;
    }
    .set_section{
      margin-bottom: 16px;
      .desc{
        color: #666;
      }
      .div_input{
        position: relative;
        margin-top: 5px;
        .div_unit{
          position: absolute;
          right: 10px;
          top: 6px;
        }
        :deep(.el-input__wrapper){
          padding: 1px 31px 1px 11px;
        }
        .rule_del{
          cursor: pointer;
        }
        .item{
          margin-bottom: 10px;
        }
        .add_btn{
          cursor: pointer;
        }
      }
      .little_input{
        width: 70px;
        margin: 0 10px;
      }
    }
  }
</style>
