<template>
  <div class="home">
    <div style="position: relative;">
      <!-- 基础信息 -->
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span class="card-title">基础信息</span>
          </div>
        </template>
        <page-add @dataChange="getWorkBasicData" :key="componentKey" ref="pageModalRef" :defaultInfo="defaultInfo"
          :modalConfig="modalConfigRef"></page-add>
      </el-card>
      <!-- 问卷配置 -->
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span class="card-title">{{ workBasicData.way === '1' ? '问卷配置' : '短信配置' }}</span>
          </div>
        </template>
        <el-row>
          <el-col :span="12">
            <el-form-item label="选择模版" label-width="200px" style="padding: 10px 40px" label-position="top" v-if="workBasicData.way === '1'">
              <el-select v-model="questionnaire" placeholder="请选择模版" style="width: 100%;">
                <el-option v-for="item in questionnaireData" :key="item.value" :label="item.title"
                  :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="选择模版" label-width="200px" style="padding: 10px 40px" v-if="workBasicData.way === '2'">
              <el-select v-model="message" placeholder="请选择模版" style="width: 100%" @change="msgTempChange">
                <el-option v-for="item in smsData" :key="item.value" :label="item.title" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <div class="templateBox" v-if="workBasicData.way === '2'">
              <div class="template-title">短信模版</div>
              <div>
                <span v-for="(node, index) in msgContent" :key="index">
                  <el-tag v-if="node.isTag" @click="node.click">{{ node.content }}</el-tag>
                  <el-link type="primary" v-if="node.isLink" @click="node.click" style="line-height: 24px;">{{
                    node.content }}</el-link>
                  <span v-if="!node.isTag && !node.isLink" v-html="node.content"></span>
                </span>
              </div>
            </div>
            <div class="templateBox" v-if="workBasicData.way === '1'">
              <div class="template-title">问卷信息</div>
              <div v-if="questionnaire" class="questionnaire">
                <fill-out :surveyId="questionnaire" :userId="'1'"></fill-out>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-card>
      <!-- 外呼坐席配置 -->
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span class="card-title">外呼坐席配置</span>
          </div>
        </template>
        <el-row>
          <el-col :span="12">
            <el-form-item label="分配方式" label-width="200px" style="padding: 10px 40px" label-position="top">
              <el-select v-model="allocation" placeholder="请选择分配方式" style="width: 100%">
                <el-option v-for="item in allotMode" :key="item.value" :label="item.title" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <div class="questionBox" style="padding-left: 40px;">
              <div class="questionBox">
                <el-table :data="seatListData" border style="margin-bottom: 15px;">
                  <el-table-column prop="userName" label="成员"></el-table-column>
                  <el-table-column prop="usercode" label="工号"></el-table-column>
                  <el-table-column prop="userdept" label="部门"></el-table-column>
                  <el-table-column label="比例(%)" v-if="allocation==='2'">
                    <template #default="scope">
                      <span v-show="scope.$index !== editIndex">{{ scope.row.proportion }}</span>
                      <el-input v-show="scope.$index === editIndex" v-model="scope.row.proportion"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="180">
                    <template #default="{ row }">
                      <div style="display: flex;">
                        <el-button link @click="handleEdit(row)" v-if="allocation==='2'">编辑</el-button>
                        <el-button type="primary" link @click="handleSave" v-if="allocation==='2'">保存</el-button>
                        <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
                <el-button class="mt-4" v-if="isdetilBtn" style="width: 100%" @click="onAddItem">
                  新增坐席
                </el-button>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-card>
      <!-- 患者匹配规则 -->
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span class="card-title">患者匹配规则</span>
          </div>
        </template>
        <el-row>
          <el-col :span="12">
            <el-form-item label="匹配方式" label-width="200px" style="padding: 0px 40px" label-position="top">
              <el-select v-model="matchingMethod" placeholder="请选择匹配方式" style="width: 100%">
                <el-option v-for="item in matchMode" :key="item.value" :label="item.title" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="去重方式" label-width="200px" style="padding: 0px 40px" label-position="top">
              <el-select v-model="deduplication" placeholder="请选择去重方式" style="width: 100%">
                <el-option v-for="item in repetitionMode" :key="item.value" :label="item.title" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="周期" label-width="200px" style="padding: 0px 40px" label-position="top">
              <el-select v-model="cycle" placeholder="请选择周期" style="width: 100%">
                <el-option v-for="item in periodData" :key="item.value" :label="item.title" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="匹配执行时间" label-width="200px" v-if="matchingMethod === '2'" style="padding: 0px 40px" label-position="top">
              <el-time-picker style="width: 100%" v-model="executionTime" placeholder="请选择时间"
                :disabled-seconds="disabledSeconds" />
            </el-form-item>
            <div style="margin: -10px 0 8px 200px;" v-if="matchingMethod === '2'">
              <el-text class="mx-1" type="danger" style="display: block;">
                执行时间占用服务资源，建议夜间选择
              </el-text>
            </div>
          </el-col>
          <el-col :span="12">
            <el-form-item label="患者数量" label-width="200px" v-if="matchingMethod === '2'" style="padding: 0px 40px" label-position="top">
              <el-radio-group v-model="patientsNumRule">
                <el-radio v-for="item in patientsData" :label="item.title" :value="item.value" :key="item.value" />
              </el-radio-group>
            </el-form-item>

            <el-form-item label="" label-width="200px" v-if="patientsNumRule!=='1'" style="padding: 0px 40px" label-position="top">
              <el-input-number v-model="patientsNum" :min="1" :max="9999" />
            </el-form-item>
          </el-col>
          
          <el-col :span="24">
            <div class="questionBox" style="padding: 0px 40px">
              <patient-list :btnFlag="isdetilBtn" :planId="planId" v-if="matchingMethod === '1' && planId"></patient-list>
              <div v-if="matchingMethod === '2'" class="border border-gray-200 rounded-lg" style="position: relative;width: 100%; padding: 30px;">
                <div>筛选条件</div>
                <el-button class="addCondition" type="primary" :icon="Plus" @click="filterAddItem">添加条件</el-button>
                <div v-for="( item, index ) in filterData" style="display: flex; margin-top: 15px;" :key="index">
                  <el-select class="formItem" v-model="item.officeItem.value" @change="officeItemChange($event,index)"
                    placeholder="请选择" style="width: 120px">
                    <el-option v-for="itemSon in item.officeItem.data" :key="itemSon.value" :label="itemSon.label"
                      :value="itemSon.value" />
                  </el-select>
                  <el-select class="formItem" v-model="item.relationItem.value" placeholder="请选择" style="width: 120px"
                    @change="relationChange($event,index)">
                    <el-option v-for="itemSon in item.relationItem.data" :key="itemSon.value" :label="itemSon.name"
                      :value="itemSon.value" />
                  </el-select>
                  <el-select class="formItem" v-model="item.numberItem.value" v-if="item.numberItem.type ==='select'"
                    placeholder="请选择" style="width: 120px">
                    <el-option v-for="itemSon in item.numberItem.data" :key="itemSon.value" :label="itemSon.name"
                      :value="itemSon.value" />
                  </el-select>
                  <el-input class="formItem" v-model="item.numberItem.value" v-if="item.numberItem.type ==='input'"
                    style="width: 120px" placeholder="请输入" />
                  <el-input-number class="formItem" v-model="item.numberItem.value"
                    v-if="item.numberItem.type ==='inputNumber'" style="width: 120px" :placeholder="item.numberItem.tip" />
                  <el-date-picker style="width: 120px" class="formItem" v-model="item.numberItem.value" v-if="item.numberItem.type ==='datetime'" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择日期" />
                  <div class="formItem">
                    <el-button :icon="Delete" type="danger" @click="filterMinuItem(index)" v-if="filterData.length > 1" />
                  </div>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-card>
      <div style="width: 100%; height: 50px;"></div>

      <div class="box-btns" v-if="isdetil!='1'&&isdetil!='2'">
        <!-- <div :class="(isdetil=='2') ? 'box-btns2':'box-btns' " v-if="isdetil!='1'&&isdetil!='2'"> -->
        <el-button style="margin-right: 30px;" type="primary" @click="handleResetClick">重置</el-button>
        <el-button style="margin-right: 30px;" type="primary" @click="handleConfirmClick">确 定</el-button>
      </div>

    </div>
    <el-dialog v-model="centerDialogVisibleQues" title="问卷信息" align-center width="30%" :modal="true" :show-close="true">
      <el-form-item label="链接：" label-width="150px">
        <el-radio-group v-model="messageType">
          <el-radio label="问卷" value="1" />
          <el-radio label="远程链接" value="2" />
        </el-radio-group>
      </el-form-item>
      <el-form-item label-width="150px" v-if="messageType === '1'">
        <el-select v-model="questionnaireMsg" placeholder="请选择模版" style="width: 240px">
          <el-option v-for="item in questionnaireData" :key="item.value" :label="item.title" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label-width="150px" v-if="messageType === '2'">
        <el-input v-model="quesIput" placeholder="请输入链接"></el-input>
      </el-form-item>
      <div style="text-align: center; margin: 0 auto;">
        <el-button type="primary" @click="centerDialogVisibleQues = false">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog v-model="centerDialogVisibleAddWorkorder" title="新增坐席" center width="550px" :modal="true"
      :show-close="true">
      <el-form-item label="请选择坐席" label-width="200px">
        <el-select v-model="seatSelectvalue" multiple filterable remote reserve-keyword placeholder="请选择坐席"
          :remote-method="remoteMethod" :loading="loading" style="width: 240px">
          <el-option v-for="item in rangeSeatData" :key="item.userName" :label="item.nickName" :value="item.userName" />
        </el-select>
      </el-form-item>
      <div style="text-align: center;">
        <el-button style="margin-right: 30px;" type="primary" @click="handleSeatTrue">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="AddFollowUpPlan">
  import {
    Plus,
    Delete
} from '@element-plus/icons-vue'
import moment from 'moment';

import PageAdd from '@/components/page-add';
import fillOut from '@/views/main/survey/fill';

import seatList from './cpns/seatList/seatList';
import patientList from './cpns/patientList/patientList';
import { modalConfig } from './config/modal.config';
import { usePageModal } from '@/hooks/use-page-add';
import useSelectStore from '@/store/commonSelect/common';
import { createPageData, editPageData, getPageListData,getPageDetail } from '@/api/main/system/system';
import { useRoute, useRouter } from 'vue-router';
import useTagsViewStore from '@/store/modules/tagsView'
import { matchTags } from '@/utils/sms'

import { 
  followType,followWay,followExecution,allotMode,repetitionMode,
  matchMode,periodData,patientsData 
} from "@/utils/commonDic.js";

import { onMounted, ref, watch, onActivated } from 'vue';
// import downLoadUrl from 'src/assets/downLoad/template.xlsx'

const props = defineProps({
  getDefaultInfo: {
    type: Object,
    default: () => ({}),
  },
  planId: {
    type: Number,
    default: 0
  },
  isdetil:{
    type: String,
    default: ''
  },
  planState: {
    type: Number,
    default: 0
  }
});

watch(props, (nweProps) => {
  console.log(planId.value, 'planId.value');
  planId.value = nweProps.planId
 
  console.log(isdetil.value, planId.value, 'planId.value')
  initMethod(nweProps);
});

const { proxy } = getCurrentInstance();

const downLoadUrl = new URL('@/assets/downLoad/template.xlsx', import.meta.url).href
const router = useRoute();
const userRouter = useRouter();
const isdetil = ref('')
const isdetilBtn = ref(true)
const componentKey = ref(0)
const loading = ref(false)
const seatSelectvalue = ref()
const rangeSeatData = ref([])
const seatData =  ref([]) 
// const seatDataList = ref([])
const seatValue = ref()
const seatListData = ref([])
const seatResultData = ref([])
const filterOfficeData = ref([])
const msgContent = ref()
const filterObjData = ref({
    officeItem:{ // 筛选项
      type: 'select',
      data: [],
      value: ''
    },
    relationItem:{ // 筛选关系
      type: 'select',
      data: [],
      value: ''
    },
    numberItem: { // 筛选输入数值
      type: 'input',
      value: ''
    }
})
const filterLongData = ref([])
const filterData = ref([])
const screenData = ref([])
const state =  ref(Number(props.planState || router.query.planState || 0));

const disabledSeconds = () => {
  return [...Array(60).keys()].filter((item) => item > 0);
}

const formData = ref({});
const workBasicData = ref({});
const questionnaireMsg = ref('')
const questionnaire = ref('') // 问卷模版id
const message = ref('') // 短信模版id
const quesIput = ref('') // 链接
const messageType = ref('1') // 短信模版问卷id
const allocation = ref('') // 分配方式 

const deduplication = ref('') // 去重方式
const matchingMethod = ref('1') // 匹配方式
const cycle = ref('') // 周期
const executionTime = ref('') // 时间
const patientsNumRule = ref('1') // 患者规则
const patientsNum = ref(1)  // 患者数量
const filterResultData = ref([])

const questionnaireData = useSelectStore().questionnaireData
const smsData = useSelectStore().templateNameListData

const centerDialogVisibleQues = ref(false)
const planId = ref(Number(router.query.planId || 0));
const planDetailObj = ref({})
const getPlanId = computed(() => {
  return router.query.planId;
});
watch(getPlanId, (nweProps) => {
  if (router.query.planId) {
    getPlanDetail(router.query.planId)
    if (router.query.planState) {
      state.value = router.query.planState
    }
  }else{
    cleanForm()
  }
});

onActivated(() => {
  console.log('onActivated')
})


onMounted(() => {
  console.log('onMounted')
  initMethod(props);
  
});

function initMethod(data) {
  isdetil.value = data.isdetil
  planId.value = data.planId
  if (planId.value) {
    getPlanDetail(planId.value)
    getPlanSeatList(planId.value)
  }
  workBasicData.value.way = '1'
  getFilterList()
  seatData.value = useSelectStore().userData
}
const centerDialogVisibleAddWorkorder = ref(false);
const onAddItem = () => {
  
  seatSelectvalue.value = []
  centerDialogVisibleAddWorkorder.value = true;

}
function messageChange(e) {
  console.log(e);
  getPageDetail("/sms/template/"+e).then((res)=>{
    console.log(res.data);
  })
  
}

function handleSeatTrue() {
  centerDialogVisibleAddWorkorder.value = false;
  if (seatSelectvalue.value.length <= 0) return;


  let newSeats = [];

  for (let i = 0; i < seatSelectvalue.value.length; i++) {
    const userCode = seatSelectvalue.value[i];

    const userInfo = seatData.value.find((o) => {
      return o.userName === userCode;
    });

    const index = seatListData.value.findIndex((o) => {
      return o.userName === userCode;
    });
    if (index < 0) {
      const info = {
        proportion: 0,
        userName: userInfo.nickName,
        usercode: userCode,
        userdept: userInfo.dept ? userInfo.dept.deptName : '',
      };

      seatListData.value.push(info);

      seatResultData.value.push(info)

      newSeats.push(info);
    }
  }

  // if (planId.value) {
  //   newAway.forEach(element => {
  //     const params = {
  //       plId:planId.value,
  //       proportion:element.proportion,
  //       userName:element.userName,
  //       usercode:element.usercode,
  //     }
  //     createPageData('/SfPlanSeats/sfplanseats',params).then((data) => {
  //           proxy.$modal.msgSuccess('新增成功！');
  //     })
  //   });
    
  // }


}

const remoteMethod = (query) => {
  if (query) {
    loading.value = true
    console.log(seatData.value, 'seatData.value');
    setTimeout(() => {
      loading.value = false
      
      rangeSeatData.value = seatData.value.filter((item) => {
        return item.nickName.toLowerCase().includes(query.toLowerCase())
      })
    }, 200)
  } else {
    rangeSeatData.value = []
  }
}
function questionHandle() {
  centerDialogVisibleQues.value = true
}
const modalConfigRef = computed(() => {
  
  //  随访类型
  const processorTypeItem = modalConfig.formItems.find((item) => item.field === 'type');
  processorTypeItem.options = followType;
  //  随访方式
  const processorwayItem = modalConfig.formItems.find((item) => item.field === 'way');
  processorwayItem.options = followWay;
  //  随访方式
  // const processorExecutionItem = modalConfig.formItems.find((item) => item.field === 'executionMethod');
  // processorExecutionItem.options = followExecution;
  
  return modalConfig;
});

// 工单基础信息
const getWorkBasicData = (item) => {
  workBasicData.value = item;
};
const listSubmitFlag = ref(false)
function listSubmit() {
  listSubmitFlag.value = true
  handleConfirmClick()
}
defineExpose({
  getWorkBasicData,
  handleResetClick,
  getPlanDetail,
  listSubmit,
  cleanForm,
});
const emit = defineEmits(['closeDrawerPlan'])

function handleResetClick(){
  emit('closeDrawerPlan', true)
}
const handleConfirmClick = () => {
  
  pageModalRef.value.formRef.ruleFormRef.validate((bool) => {
    if (bool) {
      handleFilter()
      formData.value = workBasicData.value
      formData.value.executionMethod = '1'
      // formData.value.ageing = moment(workBasicData.value.ageing).format('YYYY-MM-DD HH:mm:ss')
      formData.value.limitTime = workBasicData.value.limitTime
      formData.value.beginEffective = moment(workBasicData.value.indate[0]).format('YYYY-MM-DD HH:mm:ss')
      formData.value.endEffective = moment(workBasicData.value.indate[1]).format('YYYY-MM-DD HH:mm:ss')
      
      formData.value.questionnaire = questionnaire.value
      formData.value.message = message.value
      formData.value.messageType = messageType.value
      formData.value.messageParameter =  messageType.value==='1' ? questionnaireMsg.value : quesIput.value
      formData.value.allocation = allocation.value
      formData.value.seats = seatResultData.value 
      formData.value.deduplication = deduplication.value
      formData.value.matchingMethod = matchingMethod.value
      formData.value.cycle = cycle.value
      if (executionTime.value && executionTime.value !== 'Invalid date') {
        formData.value.executionTime = moment(executionTime.value).format('HH:mm:ss') 
      }

      // 如果是按比例分配，判断比例是否是100%
      if (allocation.value == '2' && seatListData.value.length > 0) {
        let rate = 0; seatListData.value.forEach((item) => {
          console.log(item.proportion, 'item.proportion')
          rate += +item.proportion
        })
        console.log(rate, 'item.proportion-all')
        if (rate != 100) {
          proxy.$modal.msgError('分配比例之和必须为100%')
          return;
        }
      }

      formData.value.patientsNumRule =patientsNumRule.value
      formData.value.patientsNum = patientsNum.value
      formData.value.screen = JSON.stringify(filterResultData.value)
      if (planId.value && !state.value) {
        formData.value.plId = planId.value
        editPageData('/SfPlan/sfPlan', formData.value).then((data) => {
          proxy.$modal.msgSuccess('编辑成功！');
          cleanForm()
          // 关闭当前页面
          useTagsViewStore().delView(userRouter.currentRoute.value);
          // 返回上一页面
          userRouter.push({
            path: '/followUp/followUpPlan',
          })
         
        })
      } else{
        createPageData('/SfPlan/sfPlan', formData.value).then((data) => {
            proxy.$modal.msgSuccess('新增成功！');
            cleanForm()
            if (listSubmitFlag.value) {
              listSubmitFlag.value = false
              emit('closeDrawerPlan', true)
            }else{
              // 关闭当前页面
              useTagsViewStore().delView(userRouter.currentRoute.value);
                // 返回上一页面
                userRouter.push({
                  path: '/followUp/followUpPlan',
                })
            }
            // // 关闭当前页面
            // useTagsViewStore().delView(userRouter.currentRoute.value);
            // // 返回上一页面
            // userRouter.push({
            //   path: '/followUp/followUpPlan',
            // })
        })
      }
    }
  });
};

function getPlanDetail(planId) {
  getPageDetail("/SfPlan/sfPlan/"+planId).then((res)=>{
    if (res.data) {
      planDetailObj.value = res.data
      if (planDetailObj.value.state === 2) {
        isdetilBtn.value = false
      } else{
        isdetilBtn.value = true
      }
      if (!state.value) {
        defaultInfo.value.name = planDetailObj.value.name
      }
      defaultInfo.value.type = planDetailObj.value.type.toString()
      defaultInfo.value.way = planDetailObj.value.way.toString()
      defaultInfo.value.executionMethod = planDetailObj.value.executionMethod.toString()
      // defaultInfo.value.ageing = planDetailObj.value.ageing
      defaultInfo.value.limitTime = planDetailObj.value.limitTime
      defaultInfo.value.indate = [ planDetailObj.value.beginEffective , planDetailObj.value.endEffective ]
      defaultInfo.value.describes = planDetailObj.value.describes
      if (planDetailObj.value.way.toString() === '1') {
        questionnaire.value = planDetailObj.value.questionnaire
      } else  if (planDetailObj.value.way.toString() === '2') {
        message.value = planDetailObj.value.message

        if (message.value) msgTempChange(message.value);
        messageType.value = planDetailObj.value.messageType.toString()
        if (planDetailObj.value.messageType == '1') {
          questionnaireMsg.value = Number(planDetailObj.value.messageParameter)
        }else if(planDetailObj.value.messageType == '2'){
          quesIput.value = planDetailObj.value.messageParameter
        }
      }
      allocation.value = planDetailObj.value.allocation.toString()
      deduplication.value = planDetailObj.value.deduplication.toString()
      matchingMethod.value =  planDetailObj.value.matchingMethod.toString()
      cycle.value = planDetailObj.value.cycle.toString()
      
      if (planDetailObj.value.executionTime && planDetailObj.value.executionTime !== 'Invalid date') {
        executionTime.value = converTime(planDetailObj.value.executionTime)
      } else {
        // executionTime.value = '';
      }
      patientsNumRule.value = planDetailObj.value.patientsNumRule && planDetailObj.value.patientsNumRule.toString()
      patientsNum.value = planDetailObj.value.patientsNum
      screenData.value = JSON.parse(planDetailObj.value.screen)
      if (screenData.value.length>0) {
        filterData.value = []
        screenData.value.forEach((ele, index) => {
          if (ele.field =='sex') {
            if (ele.value == '1') {
              ele.value = '男'
            }else if (ele.value == '2') {
              ele.value = '女'
            }
          }
          const obj = {
              officeItem:{
                type: 'select',
                data: filterOfficeData.value,
                value: ele.field
              },
              relationItem:{
                type: 'select',
                data: [],
                value: ele.operate
              },
              numberItem: {
                type: 'input',
                value: ele.value
              }
          }
          filterData.value.push(obj)

          // 改变输入值格式
          relationChange(ele.operate, index, 'edit');
        });
      }

    }
    
  })
}

function cleanForm() {
  componentKey.value += 1
  questionnaire.value = ''
  message.value = ''
  questionnaireMsg.value = ''
  quesIput.value = ''
  allocation.value = ''
  seatListData.value = []
  filterData.value = [{}]
  cycle.value = ''
  executionTime.value = ''
  patientsNumRule.value = ''
  patientsNum.value = ''
  screenData.value = ''
  deduplication.value = ''
  matchingMethod.value = ''
}
const converTime = (arr) => {
  const _arr = arr.split(":");
  let result = new Date(2010, 10, 10, Number(_arr[0]), Number(_arr[1]), Number(_arr[2]))
  return result
};
function getPlanSeatList(plId) {
  const params = {plId}
  getPageListData("/SfPlanSeats/sfplanseats",params).then((res)=>{
    if (res.data.length>0) {
      seatListData.value = []
      res.data.forEach((element,index) => {
        const obj = {}
        obj.userName = element.userName   
        obj.usercode = element.usercode
        
        obj.proportion = element.proportion 
        const userInfo = seatData.value.find((o) => {
          return o.userName === element.usercode;
        });

        if (userInfo) obj.userdept = userInfo.dept ? userInfo.dept.deptName : '';

        seatResultData.value.push(obj)
        seatListData.value.push(obj)
      });
    }else{
      seatResultData.value = []
      seatListData.value = []
    }
    
  })
}
const editIndex = ref(-1)
const handleEdit = (row) => {
  editIndex.value = seatListData.value.indexOf(row)
}
const handleSave = () => {
  editIndex.value = -1
}
const handleDelete = (row) => {
  
  seatResultData.value.splice(seatListData.value.indexOf(row), 1)
  seatListData.value.splice(seatListData.value.indexOf(row), 1)
}
const props2 = {
  multiple: true,
  checkStrictly: true,
}
function filterAddItem() {
  
  const newObj = {
      officeItem:{
        type: 'select',
        data: filterOfficeData.value,
        value: ''
      },
      relationItem:{
        type: 'select',
        data: [],
        value: ''
      },
      numberItem: {
        type: 'input',
        value: ''
      }
  }
  filterData.value.push(newObj) 
}

function filterMinuItem(index) {
  // 移除指定的元素
  filterData.value.splice(index, 1)
}

function handleFilter() {
  filterResultData.value = [] 
  filterData.value.forEach(ele => {
    const obj = {}
    obj.field = ele.officeItem.value
    obj.operate = ele.relationItem.value
    obj.value = ele.numberItem.value
    filterResultData.value.push(obj)
  });
}
function officeItemChange(value,index) {
  filterData.value[index].relationItem.value = ''
  filterData.value[index].numberItem.value = ''
  filterLongData.value.forEach(ele => {
    if (ele.field.value === value) {
      filterData.value[index].relationItem.data = ele.operate
      if (ele.value) {
        filterData.value[index].numberItem.type = 'select'
        filterData.value[index].numberItem.data = ele.value
      } else {
        filterData.value[index].numberItem.type = 'input'
      }
    }
  });
}

// 关系变化变更筛选框
const relationChange = (val, index, type = 'add') => {
  console.log(filterLongData, 'filterLongData');
  const curentInfo = filterData.value[index];

  if (type === 'add') {
     filterData.value[index].numberItem.value = ''
  }

  const filterOption = filterLongData.value.find((o) => {
    return o.field.value === curentInfo.officeItem.value;
  })

  

  if (!filterOption) return;

  if (type === 'edit') {
    // relationItem
    filterData.value[index].relationItem.data = filterOption.operate
    ;
  }

  // 获取关系选项
  const relationOption = filterOption.operate.find((o) => {
    return o.value === val;
  })

  if (!relationOption) return;



  if (relationOption.type === 'int') {
    filterData.value[index].numberItem.type = 'inputNumber';
  } else if (relationOption.type === 'datetime') {
    filterData.value[index].numberItem.type = 'datetime';
  } else {
    filterData.value[index].numberItem.type = 'input';
  }
  
}

function getFilterList() {
  getPageListData('/SfPlan/sfPlan/option').then((res)=>{
    if (res.data.length>0) {
      filterLongData.value = res.data
      res.data.forEach(ele => {
        const obj = {
          value:ele.field.value,
          label:ele.field.name,
        }
        filterObjData.value.officeItem.data.push(obj)
        filterOfficeData.value.push(obj)
      });
      if (screenData.value.length<1) {
        
        filterData.value.push(filterObjData.value)
      }
      
    }
  })
}

// 1.处理逻辑
const newCallback = () => { };
const editCallback = () => { };
usePageModal(newCallback, editCallback);
// 2.动态添加部门和角色列表

// 3.调用hook获取公共变量和函数
const [pageModalRef, defaultInfo] = usePageModal(newCallback, editCallback);

// 短信模板切换
const msgTempChange = (val) => {
  const msgTeml = smsData.find((o) => {
    return o.value === val;
  });
  if (msgTeml && msgTeml.content) {
    msgContent.value = matchTags(msgTeml.content, {
        url: {
            label: '问卷',
            click: questionHandle,
        },
    });
  }
}
</script>

<style scoped lang="scss">
.addCondition {
  position: absolute;
  top: 20px;
  right: 20px;
}
.home {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: #f5f7fa;
  padding: 20px;
  box-sizing: border-box;
}
.box-card {
  margin: 15px;
}

.box-btns {
  box-shadow: 0px -2px 5px rgb(176, 176, 176);
  height: 50px;
  padding: 10px;
  background-color: #ffffff;
  text-align: right;
  width: calc(100% - 200px);
  background-color: #ffffff;
  position: fixed ;
  bottom: 0px;
  z-index:3;
}
.box-btns2 {
  box-shadow: 0px -2px 5px rgb(176, 176, 176);
  height: 50px;
  padding: 10px;
  background-color: #ffffff;
  text-align: right;
  width: 100%;
  background-color: #ffffff;
  position: sticky ;
  bottom: 0px;
  z-index: 1;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .card-title {
    font-weight: bold;
    text-align: left;
  }
}

.demo-tabs>.el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

.templateBox {
  font-size: 14px;
  line-height: 32px;
  .template-title {
    margin-bottom: 15px;
  }

  .questionnaire{
    height: 300px;
    scrollbar-width: none; /* firefox */
    -ms-overflow-style: none; /* IE 10+ */
    overflow-x: hidden;
    overflow-y: auto;
  }
  
}

.questionBox {
  .filterIcon{
    position: absolute;
    right: -70px;
    bottom: 0px;
  }
  .formItem{
    margin-right: 8px;
  }
}
</style>
