<script lang="ts" setup>
import { difference } from 'lodash-es'
import {
  computed,
  defineEmits,
  defineProps,
  onMounted,
  onUnmounted,
  ref,
  watch,
} from 'vue'
import { VueDraggable } from 'vue-draggable-plus'
import { getAllfieldList, getfieldList, savefield } from '@/api/home/filter'
import { workPackageMap } from '@/config/workorder'
import { useUser } from '@/store/modules/user'

const props = defineProps({
  reviewType: {
    type: Number,
    default: () => 1,
    require: true,
  },
})

const emit = defineEmits(['onOk'])

// 左侧隐藏列表
const offList = ref<any[]>([])
// 右侧显示列表
const onList = ref<any[]>([])
// 固定默认列表
const fixList = ref<any[]>([])
// 搜索关键词
const searchKey = ref('')
const searchFixVal = ref('')
const allCount = computed(() => {
  return `全部字段(共${offList.value.length}个)`
})
const showOffList = computed(() => {
  return offList.value.filter((i) => {
    return i.name.includes(searchKey.value)
  })
})
const showFixList = computed(() => {
 
  return fixList.value.filter(i => i.name.includes(searchFixVal.value))
})
const showOnList = computed(() => {
  return onList.value.filter(i => i.name.includes(searchFixVal.value))
})
const selectCount = computed(() => {
  let baseNum = 0
  offList.value.forEach((item) => {
    if (item.fix)
      baseNum++
  })
  return `显示字段(共${baseNum + onList.value.length}个)`
})

const show = ref(false)
const checkAll = computed(() => {
  let baseNum = 0
  offList.value.forEach((v) => {
    if (v.fix)
      baseNum += 1
  })
  return onList.value.length == offList.value.length - baseNum
})
function showModal() {
  show.value = true
}

function closeModal() {
  show.value = false
}

async function handleSumbit(e: MouseEvent) {
  const userStore = useUser()
  const userInfo = userStore.getUserInfo
  let userField = ''
  fixList.value.forEach((v) => {
    userField += `${v.id},`
  })
  onList.value.forEach((v) => {
    userField += `${v.id},`
  })
  userField = userField.slice(0, userField.length - 1)
  savefield(props.reviewType, userInfo.id, userField)
  e.preventDefault()
  closeModal()
  emit('onOk')
}

defineExpose({
  showModal,
})

const selectIds = ref<string[]>([])

function onCheckAllChange(value) {
  const ids: string[] = []
  if (value) {
    offList.value.forEach((v) => {
      console.log()
      if (!v.checked)
        onList.value.push(v)
    })
  }
  else {
    onList.value = []
  }
  for (const item of offList.value) {
    if (!item.fix) {
      item.checked = value
      ids.push(item.id)
    }
  }
  selectIds.value = value ? ids : []
}

function onCheckChange(checked: any, item: any) {
  const index = selectIds.value.indexOf(item.id)

  item.checked = checked

  if (index === -1 && checked)
    selectIds.value.push(item.id)
  else selectIds.value.splice(index, 1)
}
function zhidingfun(item){
let obj = item;
let newarr= onList.value
// 先检查并移除对象是否已经存在于数组中
let index =  newarr.indexOf(obj);
if (index !== -1) {
    newarr.splice(index, 1);
}

// 使用 unshift 方法将对象放到数组的第一位
newarr.unshift(obj);
 onList.value=newarr

}
const showIds = computed(() => {
  return onList.value.map((item) => {
    return item.id
  })
})
// 关闭弹窗，清空搜索条件
watch(show, (val) => {
  if (!val) {
    searchKey.value = ''
    searchFixVal.value = ''
  }
})
watch(
  () => selectIds.value.length,
  (newVal, oldVal) => {
    if (newVal === oldVal)
      return

    const action = newVal > oldVal ? 'add' : 'remove'
    const diff
      = action === 'add'
        ? difference(selectIds.value, showIds.value)
        : difference(showIds.value, selectIds.value)

    if (diff.length === 0)
      return

    if (action === 'add') {
      for (const item of offList.value) {
        if (!item.fix && diff.includes(item.id)) {
          onList.value.push({
            id: item.id,
            name: item.name || '未配置',
            fix: item.fix || false,
          })
        }
      }
    }
    else {
      const list = onList.value
      for (let index = 0; index < list.length; index++) {
        const item = list[index]
        if (!item.fix && diff.includes(item.id)) {
          list.splice(index, 1)
          index--
        }
      }
    }
  },
)

watch(
  () => showOnList.value,
  (newVal, oldVal) => {
    console.log(showOnList.value)
 // alert(1)
  },
)

watch(
  () => showIds.value.length,
  (newVal, oldVal) => {
    if (newVal === oldVal)
      return

    const diff = difference(selectIds.value, showIds.value)

    if (diff.length === 0)
      return

    for (const item of offList.value) {
      if (!item.fix && diff.includes(item.id)) {
        const index = selectIds.value.indexOf(item.id)
        item.checked = false
        selectIds.value.splice(index, 1)
      }
    }
  },
)

function clearDragSource() {
  onList.value = onList.value.filter((item) => {
    return item.fix === true
  })
}

function removeHandler(id: string) {
  let index = onList.value.findIndex((item) => {
    return item.id === id
  })
  if (index !== -1)
    onList.value.splice(index, 1)

  index = offList.value.findIndex(v => v.id == id)
  offList.value[index].checked = false
}

function initData() {
  offList.value = []
  onList.value = []
  fixList.value = []
  // offShowList.value = [];
  // onShowList.value = [];
  // fixShowList.value = [];
  selectIds.value = []
}

async function getData() {
  initData()
  const userStore = useUser()
  const userInfo = userStore.getUserInfo
  let res
  res = await getAllfieldList(props.reviewType) // 所有筛选项目
  const allList = res.data
  res = await getfieldList(props.reviewType, userInfo.id) // 当前用户选择的项目
  const useList = res.data
  /**
   * name 标题
   * id 键值
   * fix 是否默认
   * checked 是否选中
   */
  const userFieldFixed = useList.userFieldFixed?.split(',')
  const userFieldUnFixed = useList.userFieldUnFixed?.split(',')

  allList.forEach((v) => {
    const item = {
      name: v.fieldDesc,
      id: v.name,
      fix: v.isrequired == 2,
      checked:
        v.isrequired == 2
        || Boolean(userFieldFixed?.find(v2 => v2 == v.name))
        || Boolean(userFieldUnFixed?.find(v2 => v2 == v.name)),
    }
    if (item.fix)
      fixList.value.push(item)
    else offList.value.push(item)
  })
  offList.value.unshift(...fixList.value)
  useList.userFieldFixed?.split(',').forEach((v) => {
    let item = allList.find(v2 => v2.name == v)
    if (item) {
      item = {
        name: item.fieldDesc,
        id: item.name,
        fix: item.isrequired == 2,
        checked: true,
      }
      selectIds.value.push(item.id)
      if (!item.fix)
        onList.value.push(item)
    }
  })
}
function handleKeydown(event: KeyboardEvent) {
  // 排除元素
  const eles = ['INPUT', 'TEXTAREA']
  if (!(event.target instanceof Element))
    return

  if (eles.includes(event.target.tagName))
    return
  if (event.code === 'KeyC')
    closeModal()
}
onMounted(async () => {
  getData()
  document.addEventListener('keydown', handleKeydown)
})
onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown)
})
const indeterminate = computed(() => {
  let baseNum = 0
  offList.value.forEach((v) => {
    if (v.fix)
      baseNum += 1
  })
  return onList.value.length > 0 && offList.value.length - baseNum > onList.value.length
})
</script>

<template>
  <n-modal v-model:show="show" transform-origin="center">
    <n-card
      class="cardstyle"
      :bordered="false"
      size="huge"
      role="dialog"
      aria-modal="true"
    >
      <div class="wrapper">
        <span class="wrapper-title" style="color: #333">自定义任务包字段</span>
        <div class="wrapper-bar">
          <div class="wrapper-info">
            <span :style="{ 'margin-left': '18px' }">字段信息</span>
          </div>
        </div>
        <n-grid cols="24" class="mt-4 proCard" responsive="screen" :x-gap="24">
          <n-grid-item span="17">
            <NCard
              :title="allCount"
              class="dragcardStyle"
            
              :segmented="{ content: true, footer: true }"
              size="small"
              :bordered="false"
            >
              <div class="left">
                <n-input v-model:value="searchKey" placeholder="搜索关键词">
                  <template #suffix>
                    <SvgIcon size="16" name="magnifying-1-color999" />
                  </template>
                </n-input>
                <div class="draggable-ul">
                  <div class="draggable-li" :class="{ checkAll: indeterminate }">
                    <n-checkbox
                      v-model:checked="checkAll"
                      label="全选"
                      :indeterminate="indeterminate"
                      @update:checked="onCheckAllChange"
                    />
                  </div>
                  <div class="content">
                    <div
                      v-for="item in showOffList"
                      :key="item.id"
                      style="width: 165px"
                      :class="{ 'disable-check': item.fix }"
                      class="draggable-li"
                    >
                      <n-checkbox
                        v-model:checked="item.checked"
                        :label="item.name"
                        :disabled="item.fix"
                        @update:checked="onCheckChange($event, item)"
                      />
                    </div>
                  </div>
                </div>
              </div>
            </NCard>
          </n-grid-item>
          <n-grid-item>
            <NCard
              :title="selectCount"
              class="dragcardStyle"
              style="width: 216px;"
              :segmented="{ content: true, footer: true }"
              size="small"
              :bordered="false"
            >
              <template #header-extra>
                <span class="textbtnStyle" @click="clearDragSource">恢复默认</span>
              </template>
              <div class="overstyle">
                <n-input v-model:value="searchFixVal" placeholder="搜索关键词">
                  <template #suffix>
                    <SvgIcon size="16" name="magnifying-1-color999" />
                  </template>
                </n-input>
                <div class="titletwo">系统默认</div>
             
                <div class="draggable-ul">
                  <div
                    v-for="item in showFixList"
                    :key="item.id"
                    :class="{ fix: item.fix }"
                    class="cursor-move draggable-item"
                  >
                   <SvgIcon name="drag" size="14" />
                    <span class="ml-2" style="color: #666">{{ item.name }}</span>
                  </div>
                </div>
                   <div class="titletwo">自定义配置</div>
                <VueDraggable
                  v-model="onList"
                  class="draggable-ul"
                  :animation="150"
                  group="shared"
                >
                  <div
                    v-for="item in onList"
                    :key="item.id"
                    :class="{ fix: item.fix }"
                    class="cursor-move draggable-item"
                  >
                    <SvgIcon name="drag" size="14" />
                    <span class="ml-2">{{ item.name }}</span>
            
                  <div class="zhiding" @click="zhidingfun(item)">
                     <n-popover trigger="hover"  placement="bottom">
                 <template #trigger>
                      <SvgIcon
                      v-if="!item.fix"
                      size="16px"
                      style="display: block; cursor: pointer;position:absolute;    right: 50px; top:14.5px"                     
                      name="topbt"

                    />
                      </template>
                       <span>置顶</span>
               </n-popover>
                </div>
                    <SvgIcon
                      v-if="!item.fix"
                      size="16px"
                      style="display: block; margin-left: auto; cursor: pointer"
                      name="clear"
                      @click="removeHandler(item.id)"
                    />
                  </div>
                </VueDraggable>
              </div>
            </NCard>
          </n-grid-item>
        </n-grid>
      </div>
      <template #footer>
        <div class="wrapper-footer">
          <n-button type="info" style="background-color: #507afd" @click="handleSumbit">
            确定
          </n-button>
          <n-button
            secondary
            style="margin-left: 15px"
            @click="
              getData();
              closeModal();
            "
          >
            取消
          </n-button>
        </div>
      </template>
    </n-card>
  </n-modal>
</template>

<style lang="less" scoped>
.wrapper {
  display: flex;
  flex-direction: column;
  border-bottom: 1px solid #e8e8e8;
  padding-bottom: 32px;

  &-title {
    font-weight: bold;
    font-size: 16px;
  }

  &-bar {
    width: 100%;
    margin-top: 20px;
  }

  &-footer {
    display: flex;
    justify-content: flex-end;
  }

  &-info {
    font-weight: bold;
    position: relative;
    color: #333333;
    font-size: 14px;

    &:before {
      background-color: #507afd;
      content: "";
      width: 5px;
      border-radius: 2px;
      top: 0;
      bottom: 0;
      position: absolute;
    }
  }
}

.dragcardStyle {
  --n-padding-bottom: 0px !important;
  --n-padding-left: 0px !important;
}

.cardstyle {
  width: 808px;
  height:746px;
  --n-padding-bottom: 20px;
  --n-padding-left: 24px;
}

.textbtnStyle {
  cursor: pointer;
  color: #1980ff;
}

.draggable-ul {
  width: 100%;
  
  overflow: hidden;
  border: 1px solid #cad2dd;
  border-top: 0px;
  border-radius: 2px;
  display: block;

  .content {
    display: flex;
    flex-wrap: wrap;
  }

  .draggable-li {
    padding: 10px 16px;
    color: #333;
  }

  .draggable-item {
    padding: 11px 16px;
    color: #333;
    display: flex;
    align-items: center;
    position: relative;

  }

  .disable-check {
    color: gainsboro;
  }
}
.overstyle{
      height: 474px;
    overflow: auto;
    border:1px solid #cad2dd
}
  /* 定义滚动条的宽度及背景颜色 */
  ::-webkit-scrollbar {
    position: fixed;
    width: 5px; /* for vertical scrollbars */
    height: 10px; /* for horizontal scrollbars */
    background: #f1f1f1;
  }

  /* 定义滚动条轨道的样式 */
  ::-webkit-scrollbar-track {
    background-color: #e1e1e1;
    border-radius: 10px; /* 圆角 */
  }

  /* 定义滚动条滑块的样式 */
  ::-webkit-scrollbar-thumb {
    background-color: #888;
    border-radius: 10px; /* 圆角 */
  }

  /* 滑块hover时的样式 */
  ::-webkit-scrollbar-thumb:hover {
    background-color: #555;
  }
    ::v-deep(.draggable-ul){
     border: none;
    }
  .left{
    ::v-deep(.draggable-ul){
      height: 444px;
      border: 1px solid #cad2dd;
    }
  }
  .titletwo{
  margin: 10px;
height: 20px;
font-size: 14px;
font-family: PingFang SC, PingFang SC-Regular;
font-weight: Regular;
text-align: left;
color: #999999;
line-height: 20px;
    margin-top: 12px;
    margin-left: 16px;
  }
::v-deep(.n-card.n-card--content-segmented > .n-card__content:not(:first-child)) {
  border: 0px;

}

::v-deep(.n-card > .n-card-header) {
  --n-padding-top: 0px;
  --n-padding-bottom: 12px;
}
::v-deep(.n-card > .n-card-header .n-card-header__main) {
  font-weight: lighter !important;
  font-size: 14px;
}
::v-deep(.n-scrollbar) {
  border-top: none !important;
}
::v-deep(.n-button--info-type) {
  background: #507afd !important;
}
::v-deep(.checkAll .n-checkbox.n-checkbox--indeterminate .n-checkbox-box) {
  background: none;
  border: none;
}
::v-deep(.checkAll .n-checkbox-box__border) {
  border: 1px solid #e8e8e8 !important;
}
::v-deep(.checkAll .n-checkbox-icon) {
  border: 3px solid #fff;
  background: #1980ff;
}
::v-deep(.checkAll .n-checkbox-icon svg) {
  display: none !important;
}
::v-deep(.n-card-header__main) {
  color: #666 !important;
}
::v-deep(.n-button--secondary) {
  background-color: #fff;
  border: 1px solid #cad2dd !important;
}
::v-deep(.n-button--secondary):hover {
  background-color: #fff !important;
  border: 1px solid #cad2dd !important;
}
.zhiding{
  display: none;
}
  .draggable-item:hover {
   .zhiding{
  display: block;
}

  }
</style>
