<template>
  <div class="home">
    <el-form :rules="rules" :model="ruleForm" ref="ruleFormRef">
      <div style="position: relative;">
        <!-- 基础信息 -->
        <div class="box-card" style="padding-top: 0px;">
          <div class="card-title">基础信息</div>
          <div class="card-content">
            <el-row>
              <el-col :span="20">
                <el-form-item label="任务名称" prop="name" label-width="150px">
                  <el-input v-model="ruleForm.name" />
                </el-form-item>
                <el-form-item label="任务描述" prop="content" label-width="150px">
                  <el-input v-model="ruleForm.content" type="textarea" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>

        <!-- 抽查范围 -->
        <div class="box-card">
          <div class="card-title">抽查范围</div>
          <div class="card-content">
            <el-row>
              <el-col :span="20">
                <el-form-item label="起止日期" label-width="150px">
                  <el-date-picker v-model="ruleForm.startTime" type="daterange" range-separator="~"
                    start-placeholder="开始日期" end-placeholder="截止日期" @change="clearRange" />
                </el-form-item>

                <el-form-item label="抽查对象" label-width="150px" @change="objChange">
                  <el-radio-group v-model="ruleForm.spotCheckObject" @change="clearRange">
                    <el-radio-button label="按类型" value="1" />
                    <el-radio-button label="按科室" value="2" />
                    <el-radio-button label="按人员" value="3" />
                  </el-radio-group>
                </el-form-item>

                <el-form-item label="随访方式" label-width="150px">
                  <el-radio-group v-model="ruleForm.executionMethod" @change="clearRange">
                    <el-radio value="">全部</el-radio>
                    <el-radio value="2">智能</el-radio>
                    <el-radio value="1">人工</el-radio>
                  </el-radio-group>
                </el-form-item>

                <el-form-item label="执行方式" label-width="150px" @change="clearRange">
                  <el-radio-group v-model="ruleForm.way">
                    <el-radio value="">全部</el-radio>
                    <el-radio value="1">电话</el-radio>
                    <el-radio value="2">短信</el-radio>
                  </el-radio-group>
                </el-form-item>

                <el-form-item label="抽查数量" label-width="150px">
                  <el-radio-group v-model="ruleForm.allocation">
                    <el-radio value="2">按比例</el-radio>
                    <el-radio value="1">定量</el-radio>
                  </el-radio-group>
                </el-form-item>

              </el-col>
            </el-row>

            <div class="questionBox">
              <el-table :data="ruleForm.examinationRange" border style="margin-bottom: 15px;">
                <el-table-column fixed="left" prop="name"
                  :label="['类型', '科室', '人员'][Number(ruleForm.spotCheckObject) - 1]" width="150">
                  <template #default="scope">
                    <el-cascader style="width: 120px"
                      v-if="scope.$index === editRowNumber && ruleForm.spotCheckObject.toString() === '2'"
                      v-model="scope.row.name" placeholder="请选科室" :options="deptData" filterable
                      @change="nameChange(scope.row, scope.$index)" />

                    <el-select v-else-if="scope.$index === editRowNumber && ruleForm.spotCheckObject.toString() === '1'"
                      v-model="scope.row.name" filterable placeholder="请选择类型" style="width: 120px"
                      @change="nameChange(scope.row, scope.$index)">
                      <el-option v-for="item in typeData" :key="item.value" :label="item.title" :value="item.value" />
                    </el-select>

                    <el-select v-else-if="scope.$index === editRowNumber && ruleForm.spotCheckObject.toString() === '3'"
                      v-model="scope.row.name" filterable placeholder="请选择人员" style="width: 120px"
                      @change="nameChange(scope.row, scope.$index)">
                      <el-option v-for="item in seatData" :key="item.value" :label="item.title" :value="item.value" />
                    </el-select>

                    <span v-else>{{ scope.row.name }}</span>

                  </template>
                </el-table-column>

                <el-table-column prop="total" label="总量" width="80"></el-table-column>
                <el-table-column prop="spotChecked" label="已抽查" width="80"></el-table-column>
                <el-table-column prop="spotCheck" label="可抽查" width="80"></el-table-column>
                <el-table-column prop="proportion" :label="['数量', '比例(%)' ][Number(ruleForm.allocation) - 1]"
                  width="100">
                  <template #default="scope">
                    <span v-show="scope.$index !== editRowNumber">{{ scope.row.proportion }}</span>
                    <el-input v-show="scope.$index === editRowNumber" v-model="scope.row.proportion"></el-input>
                  </template>
                </el-table-column>

                <el-table-column fixed="right" label="操作" width="100">
                  <template #default="scope">
                    <div style="display: flex;">
                      <el-button link @click="handleEdit(scope.$index)"
                        v-if="editRowNumber !== scope.$index">编辑</el-button>
                      <el-button type="primary" link @click="handleSave" v-else>保存</el-button>
                      <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
              <el-button class="mt-4" v-if="isdetilBtn" style="width: 100%" @click="onAddItem">
                {{ objTitle }}
              </el-button>
            </div>
          </div>
        </div>

        <!-- 时间范围 -->

        <div class="box-card" style="border-bottom: none;">
          <div class="card-title">时间范围</div>
          <div class="card-content">
            <el-row>
              <el-col :span="20">
                <el-form-item label="周期性" label-width="150px">
                  <el-radio-group v-model="ruleForm.cycle">
                    <el-radio value="1">一次性</el-radio>
                    <el-radio value="2">每天</el-radio>
                    <el-radio value="3">每周</el-radio>
                    <el-radio value="4">每月</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="时间" v-if="ruleForm.cycle == '2'" label-width="150px">
                  <el-time-select v-model="ruleForm.executionDate" placeholder="选择时间">
                  </el-time-select>

                </el-form-item>
                <el-form-item label="周" v-if="ruleForm.cycle == '3'" label-width="150px">
                  <el-checkbox-group v-model="ruleForm.executionDate">
                    <el-checkbox label="周一" value="2" />
                    <el-checkbox label="周二" value="3" />
                    <el-checkbox label="周三" value="4" />
                    <el-checkbox label="周四" value="5" />
                    <el-checkbox label="周五" value="6" />
                    <el-checkbox label="周六" value="7" />
                    <el-checkbox label="周日" value="1" />

                  </el-checkbox-group>
                </el-form-item>
                <el-form-item label="月" v-if="ruleForm.cycle == '4'" label-width="150px">
                  <el-checkbox-group v-model="ruleForm.executionDate">
                    <el-checkbox v-for="item in 30" :key="item" :label="`${item}号`" :value="item"
                      style="width: 50px;" />

                  </el-checkbox-group>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>

      </div>
    </el-form>
  </div>
</template>

<script setup name="AddFollowUpPlan" lang="ts">
import {
  Plus,
  Minus
} from '@element-plus/icons-vue'

import fillOut from '@/views/main/questionnaireManagement/fillOut';

import seatList from './cpns/seatList/seatList';
import patientList from './cpns/patientList/patientList';
import { modalConfig } from './config/modal.config';
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 moment from 'moment'

import { followType } from "@/utils/commonDic.js";

import { onMounted, ref, watch, reactive, defineExpose } 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: ''
  }
});
watch(props, (nweProps) => {
  planId.value = nweProps.planId
  initMethod(nweProps);
});

const ruleFormRef = ref(null);

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 loading = ref(false)
const seatSelectvalue = ref()
const rangeSeatData = ref([])
const seatData: any = ref([])
const typeData: any = ref([])
const deptData = ref([])
const seatDataList = ref([])
const seatValue = ref()
const seatListData = ref([])
const filterOfficeData = ref([])
const editRowNumber = ref(-1)
const ruleForm: any = ref({
  name: '',
  content: '',
  startTime: [],
  spotCheckObject: '1',
  executionMethod: '1',
  way: '1',
  allocation: '1',
  examinationRange: [],
  cycle: 1,
  executionDate: [],
})

const rules = reactive({
    name: [
      { required: true, message: '名称不能为空' },
      {
        max: 50,
        message: '最大50字符',
      },
    ],
    content: [
      {
        max: 100,
        message: '最大100字符',
      },
    ],
    startTime: [
      { required: true, message: '请选择起止时间' },
    ]
});
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(router.query.planState || 0));

const formData = 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()
  }
});


onMounted(() => {
  initMethod(props);

});
const props1 = {
  multiple: true,
  checkStrictly: true,
}

function initMethod(data) {
  isdetil.value = data.isdetil
  if (planId.value) {
    getPlanDetail(planId.value)
  }
  getFilterList()
  getSeatList()

  typeData.value = followType
  deptData.value = useSelectStore().deptListData
  seatData.value = useSelectStore().userListData

}
function deptChange(e) { }
const objTitle = ref('新增类型')
function objChange(e) {
  console.log(e.target._value)
  if (e.target._value === '1') {
    objTitle.value = '新增类型'
  } else if (e.target._value === '2') {
    objTitle.value = '新增科室'
  } else if (e.target._value === '3') {
    objTitle.value = '新增人员'
  }
  seatListData.value = []
}
function getSeatList() {
  getPageListData('/system/user').then((res) => {
    seatDataList.value = res.data
  })
}

const centerDialogVisibleAddWorkorder = ref(false);
const onAddItem = () => {
  if (!ruleForm.value.examinationRange) ruleForm.value.examinationRange = [];

  ruleForm.value.examinationRange.push({
    name: '',
    number: 0,
    proportion: 0,
    spotCheck: 0,
    spotChecked: 0,
    total: 0,
  })

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

}

function handleSeatTrue() {
  centerDialogVisibleAddWorkorder.value = false;
  console.log(seatSelectvalue.value)
  if (objTitle.value === '新增科室') {
    const newAway = []
    seatSelectvalue.value.forEach((ele) => {

      newAway.push(ele[ele.length - 1])
    })
    seatSelectvalue.value = newAway
  }
  seatSelectvalue.value.forEach((element) => {
    const obj = {}
    if (ruleForm.value.radio1 === '1') {
      obj.typeName = element
    } else if (ruleForm.value.radio1 === '2') {
      obj.deptName = element
    } else if (ruleForm.value.radio1 === '3') {
      obj.userName = element
    }
    obj.grossNum = 100
    obj.alreadyNum = 20
    obj.mayNum = 80
    seatListData.value.push(obj)
  })

}

const remoteMethod = (query) => {
  if (query) {
    loading.value = true
    setTimeout(() => {
      loading.value = false
      rangeSeatData.value = seatData.value.filter((item) => {
        return item.title.toLowerCase().includes(query.toLowerCase())
      })
    }, 200)
  } else {
    rangeSeatData.value = []
  }
}

function questionHandle() {
  centerDialogVisibleQues.value = true
}

const emit = defineEmits(['closeDrawerPlan'])

function handleResetClick() {
  emit('closeDrawerPlan', true)
}
const handleConfirmClick = () => { };

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
      }

      deduplication.value = planDetailObj.value.deduplication.toString()
      matchingMethod.value = planDetailObj.value.matchingMethod.toString()
      cycle.value = planDetailObj.value.cycle.toString()

      executionTime.value = converTime(planDetailObj.value.executionTime)
      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 => {
          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)
        });
      }


    }

  })
}

function cleanForm() {
  questionnaireMsg.value = ''
  seatListData.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
};

const editIndex = ref(-1)
const handleEdit = (rowIndex) => {
  editRowNumber.value = rowIndex
}
const handleSave = () => {
  editRowNumber.value = -1
}
const handleDelete = (row) => {
  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() {
  filterData.value.pop()
}

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) {
  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'
      }
    }
  });
}
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)
      }

    }
  })
}

const nameChange = (row, index) => {
  // 获取数量
  console.log(ruleForm.value, 'ruleForm.value')
  getPageListData('/examination/rules/getPatientNumber', {
    startTime: moment(ruleForm.value.startTime[0]).format('YYYY-MM-DD HH:mm:ss'),
    endTime: moment(ruleForm.value.startTime[1]).format('YYYY-MM-DD HH:mm:ss'),
    executionMethod: ruleForm.value.executionMethod,
    spotCheckObject: ruleForm.value.spotCheckObject,
    way: ruleForm.value.way,
  }).then(res => {
    if (res.data) {
      ruleForm.value.examinationRange[index].spotCheck = res.data.spotCheck || 0
      ruleForm.value.examinationRange[index].spotChecked = res.data.spotChecked || 0
      ruleForm.value.examinationRange[index].total = res.data.total || 0
    }
  })
}

const clearRange = () => {
  ruleForm.value.examinationRange = []
}

const submit = () => {
  console.log('submit')
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      console.log(ruleForm.value, 'ruleForm.value')
    }
  })
}


defineExpose({
  submit,
  handleResetClick,
})

</script>

<style scoped lang="scss">
.box-card {
  border-bottom: 1px solid #DCDFE6;
  padding: 30px 20px;

  .card-title {
    font-weight: bold;
    font-size: 16px;
    color: #303133;
    margin-bottom: 10px;
    text-align: left;
  }

  .card-content {
    .questionBox {
      width: 90%;
      margin: 0 auto;

      .filterIcon {
        position: absolute;
        right: -70px;
        bottom: 0px;
      }

      .formItem {
        margin-right: 8px;
      }
    }
  }
}

.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;
}
</style>