<template>
  <a-card style="background-color:#f0f0f0;">
    <template #extra>
      <a-button type="primary" @click="handleSubmit" style="margin-right: 50px;">保存</a-button>
    </template>
    <a-row :gutter="10" style="padding: 0px">
      <a-col :span="10">
        <a-card title="相关配置">
          <div  class="inner-card">
            <BasicForm @register="registerRelationForm" />
          </div>
        </a-card>
      </a-col>

      <a-col :span="14">
        <a-card title="外包商属性">
          <div  class="inner-card">
            <a-tree
              ref="treeRef"
              checkable
              :tree-data="treeApiData"
              :showLine="false"
              v-model:expandedKeys="expandedKeys"
              v-model:checkedKeys="checkedKeys"
              @select="clickNode"
              default-expand-all="true"
            />
          </div>
        </a-card>
      </a-col>
    </a-row>
  </a-card>
</template>
<script lang="ts" setup>
  import { ref, onMounted,nextTick } from 'vue';
  import { message } from 'ant-design-vue';
  import { useForm, BasicForm, } from '/@/components/Form';
  import { FormSchema } from '/@/components/Table';
  import {saveOrUpdate,listAll } from './config/WbCheckCfg.api'

  import { defHttp } from '/@/utils/http/axios';
import { any } from 'vue-types';

  const expandedKeys = ref<string[]>(['0-2']);
  
  const checkedKeys = ref(['0-2']);
  const curOldExist = ref(['']);

  const treeRef = ref();
  const treeApiData = ref([]);
  const curApiId = ref();
  const allExistData = ref([]);

  const formRelationSchema: FormSchema[] = [
  {
    label: '外包商分级',
    field: 'wbLevel',
    component: 'JDictSelectTag',
    componentProps: {
      dictCode: 'wb_level',
      type:'radio',
      onChange: async (val) => {
        setTreeSelect()
      }
    },
    colProps: { span: 24 },
    required:true,
    
  },
  {
    label: '外包商服务',
    field: 'wbServiceTp',
    component: 'JDictSelectTag',
    componentProps: {
      dictCode: 'wb_service_tp',
      type:'radio',
      //mode: 'multiple',
      onChange: async (val) => {
        setTreeSelect()
      }
    },
    required:true,
    colProps: { span: 24 },
  },
  {
    label: '服务场所',
    field: 'wbWorkplaceTp',
    component: 'JDictSelectTag',
    componentProps: {
      dictCode: 'wb_workplace_tp',
      type:'radio',
      onChange: async (val) => {
        setTreeSelect()
      }
    },
    colProps: { span: 24 },
    required:true,
  },
];

  const [registerRelationForm, { setProps, resetFields, setFieldsValue, validate }] = useForm({
    schemas: formRelationSchema,
    showActionButtonGroup:false,
  });



  async function handleSubmit() {
  try {
    if (checkedKeys.value.length === 0) {
      message.warning("请选择外包商属性");
      return false;
    }

    const tidAry = checkedKeys.value
      .filter(item => !item.includes('_')) // 排除带下划线的项
      .filter(item => !curOldExist.value.includes(item)); // 排除已存在的项
    const formValues = await validate();
    const submitData = {
      tids: tidAry,
      ...formValues
    };

    await saveOrUpdate(submitData, false);

    curOldExist.value = checkedKeys.value

    return true;
    
  } catch (error) {
    console.error("提交失败:", error);
    return false;
  }
}

  const queryApiTreeForDetail = '/wb.manage/wbCompanyDetail/queryApiTreeForDetail';

  async function clickNode(selectedKeys, e: { selected: Boolean; selectedNodes; node; event }) {
    if (e.selected) {
      if (!e.node.children) {
        curApiId.value = e.node.code;
      }
    }
  }


  async function initApiData() {
    treeApiData.value = await defHttp.get({ url: queryApiTreeForDetail });
    allExistData.value = (await listAll({})).map(item => ({
      ...item,
      tid: String(item.tid)  // 确保 tid 是字符串
    }));
  }




  async function setTreeSelect() {
    const formVal = await validate();
    const result = await allExistData.value.filter(item => 
      item.wbLevel ==formVal.wbLevel &&
      item.wbServiceTp == formVal.wbServiceTp &&
      item.wbWorkplaceTp == formVal.wbWorkplaceTp
    );
    checkedKeys.value = curOldExist.value =  [...new Set(result.map(item => item.tid))];

  }



  onMounted(async () => {
    await initApiData();
  });



</script>
<style scoped>
  .tree-transfer .ant-transfer-list:first-child {
    width: 50%;
    flex: none;
  }

  :deep(.ant-card-body) {
    padding: 0px;
  }

  :deep(.ant-card-head) {
    padding: 0px 10px;
    min-height: 30px;
  }

  .inner-card {
    height: 65vh; 
    overflow-y: auto;
    padding: 10px;
    margin: 10px;
  }
</style>