<template>
  <div class="w-full h-full flex flex-col" v-if="state.isInit">
    <div class="flex-1">
      <CzrContent
        v-model:tableHead="state.query.tableHead"
        @handleReset="onReset"
        @handleSearch="onSearch"
        v-model:full="state.query.isFull"
      >
        <template #fieldOut>
          <CzrForm label-width="auto" @handleEnter="onSearch">
            <CzrFormColumn
              :span="6"
              label="名称"
              v-model:param="state.query.form.name"
            />
            <CzrFormColumn
              :span="6"
              label="别名"
              v-model:param="state.query.form.alias"
            />
            <CzrFormColumn
              :span="6"
              label="CAS号"
              v-model:param="state.query.form.casNo"
            />
            <CzrSearchButtons @handleSearch="onSearch" @handleReset="onReset" />
          </CzrForm>
        </template>
        <template #tableTitle>
          <div class="flex gap-[10px]">
            <CzrButton type="import" title="Excel导入" @click="onExcelImport" />
            <CzrButton type="import" title="文本导入" @click="onTextImport" />
            <CzrButton type="add" title="新增" @click="onAdd" />
            <CzrButton type="del" title="清空全部" @click="onClear" />
          </div>
        </template>
        <template #table>
          <CzrTable
            v-loading="state.query.loading"
            ref="ref_cusTable"
            :data="tableDataCpt"
            :head="state.query.head"
            :total="state.allSelected.size"
            :page="state.query.page.pageNum"
            :pageSize="state.query.page.pageSize"
            @handlePage="onPage"
          >
            <template #reserves-column-value="{ scope }">
              <CzrFormColumn
                class="__czr-table-form-column"
                label-width="0px"
                :span="24"
                v-model:param="scope.row.reserves"
                link="number"
                :min="0.00001"
                :decimal="5"
              />
            </template>
            <template #caozuo-column-value="{ scope }">
              <div class="__czr-table-operations">
                <CzrButton
                  type="table-del"
                  @click="() => state.allSelected.delete(scope.row.id)"
                />
              </div>
            </template>
          </CzrTable>
        </template>
      </CzrContent>
    </div>
    <div class="w-full flex justify-center gap-[10px] py-[20px]">
      <div class="__czr-dialog-foot_submit __hover" @click="onSubmit">确定</div>
      <div class="__czr-dialog-foot_cancel __hover" @click="onCloseIframe">
        取消
      </div>
    </div>
    <listCom
      v-model:show="state.list.show"
      :transfer="state.list.transfer"
      @refresh="onGetList"
    />
    <textImportCom
      v-model:show="state.textImport.show"
      :transfer="state.textImport.transfer"
      @refresh="onGetTextImport"
    />
    <excelImportCom
      v-model:show="state.excelImport.show"
      :transfer="state.excelImport.transfer"
      @refresh="onGetExcelImport"
    />
  </div>
</template>

<script setup lang="ts">
import {
  computed,
  getCurrentInstance,
  h,
  onBeforeMount,
  onMounted,
  provide,
  reactive,
  ref,
} from 'vue'
import listCom from './list.vue'
import textImportCom from './text-import.vue'
import excelImportCom from './excel-import.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { useRoute } from 'vue-router'
import { useDictionaryStore } from '@/stores'
import CzrFormColumn from '@/components/czr-ui/CzrFormColumn.vue'
import { isValue } from '@/utils/czr-util'

const route = useRoute()
const DictionaryStore = useDictionaryStore()
const emit = defineEmits([])
const props = defineProps({})
const { proxy }: any = getCurrentInstance()
const state: any = reactive({
  isInit: false,
  query: {
    loading: false,
    head: [
      { value: 'name', label: '名称', show: true },
      { value: 'alias', label: '别名', show: true },
      { value: 'casNo', label: 'CAS号', show: true },
      {
        value: 'haveOrNo',
        label: '有/无存储',
        show: true,
        dictList: DictionaryStore.businessModelHaveOrNoList,
      },
      {
        value: 'reserves',
        label: '储量(m³/吨)',
        show: true,
        required: route.query.haveOrNo == 1,
      },
      {
        value: 'caozuo',
        label: '操作',
        show: true,
        width: 300,
        fixed: 'right',
        popover: false,
      },
    ],
    page: {
      pageNum: 1,
      pageSize: 20,
    },
    form: {},
    formReal: {},
    result: {
      total: 0,
      data: [],
    },
  },
  formMessage: null,
  allSelected: new Map(),
  list: {
    show: false,
    transfer: {},
  },
  textImport: {
    show: false,
    transfer: {},
  },
  excelImport: {
    show: false,
    transfer: {},
  },
})
const ApiProxy = ref(`${import.meta.env.DEV ? '' : location.origin}/wForm`)
provide('ApiProxy', ApiProxy)
provide('haveOrNo', route.query.haveOrNo)
const tableDataCpt = computed(() => {
  let arr = [...Array.from(state.allSelected.values())]
  //  添加表单参数
  for (const [k, v] of Object.entries(state.query.formReal)) {
    if (proxy.$czrUtil.isValue(v)) {
      arr = arr.filter((d: any) => d[k].includes(v))
    }
  }
  return arr.slice(
    (state.query.page.pageNum - 1) * state.query.page.pageSize,
    state.query.page.pageNum * state.query.page.pageSize,
  )
})
const onPage = (pageNum, pageSize) => {
  state.query.page = {
    pageNum: pageNum,
    pageSize: pageSize,
  }
}
const onSearch = () => {
  state.query.formReal = JSON.parse(JSON.stringify(state.query.form))
  onPage(1, state.query.page.pageSize)
}
const onReset = () => {
  state.query.form = {}
  onSearch()
}
const onAdd = () => {
  state.list.transfer = {
    allSelected: state.allSelected,
  }
  state.list.show = true
}
const onGetList = (map) => {
  const newIds: any = []
  map.forEach((v) => {
    newIds.push(v.id)
    v.haveOrNo = route.query.haveOrNo
    if (!state.allSelected.has(v.id)) {
      state.allSelected.set(v.id, JSON.parse(JSON.stringify(v)))
    }
  })
  Array.from(state.allSelected.keys()).forEach((v) => {
    if (!newIds.includes(v)) {
      state.allSelected.delete(v)
    }
  })
}
const onClear = () => {
  ElMessageBox.confirm('请确认是否清空全部数据？', '提示')
    .then(() => {
      state.allSelected.clear()
    })
    .catch(() => {})
}
const onTextImport = () => {
  state.textImport.transfer = {}
  state.textImport.show = true
}
const onGetTextImport = (arr) => {
  arr.forEach((v) => {
    v.haveOrNo = route.query.haveOrNo
    if (!state.allSelected.has(v.id)) {
      state.allSelected.set(v.id, v)
    }
  })
}
const onExcelImport = () => {
  state.excelImport.transfer = {}
  state.excelImport.show = true
}
const onGetExcelImport = (arr) => {
  arr.forEach((v) => {
    v.haveOrNo = route.query.haveOrNo
    if (!state.allSelected.has(v.id)) {
      state.allSelected.set(v.id, v)
    }
  })
}
const onSubmit = () => {
  const list: any = Array.from(state.allSelected.values())
  const ids = Array.from(state.allSelected.keys()).join(',')
  if (route.query.haveOrNo == 1) {
    for (let i = 0; i < list.length; i++) {
      if (!isValue(list[i].reserves)) {
        ElMessage({
          // dangerouslyUseHTMLString: true,
          // grouping: true,
          // message: `${state.query.head.filter((v) => v.value === 'reserves')[0].label}不可为空（第${Math.ceil((i + 1) / state.query.page.pageSize)}页，第${(i + 1) % state.query.page.pageSize}条数据，<span class="__hover text-[var(--czr-main-color)]" @click="onReset">重置查询</span>）`,
          type: 'warning',
          message: h(
            'span',
            {
              class: 'text-[14px] text-[var(--czr-warning-color)]',
            },
            [
              h(
                'span',
                null,
                `${state.query.head.filter((v) => v.value === 'reserves')[0].label}不可为空（第${Math.ceil((i + 1) / state.query.page.pageSize)}页，第${(i + 1) % state.query.page.pageSize}条数据）`,
              ),
              Object.keys(state.query.formReal).length > 0
                ? h(
                    'span',
                    {
                      class: '__hover text-[var(--czr-main-color)] font-bold',
                      onClick: onReset,
                    },
                    '重置查询',
                  )
                : undefined,
            ],
          ),
        })
        return
      }
    }
  }
  axios
    .post(
      `${ApiProxy.value}/api/blade-dcms/hazardouschemicalscatalog/selectCatalogStrBYIds`,
      {
        ids: ids,
        apiname: import.meta.env.VITE_API_NAME,
      },
      {},
    )
    .then((res: any) => {
      if (res.data.code == 0) {
        const strs = res.data.data
        onConfirmIframe({ wfIds: ids, wfList: list, wfStrs: strs })
      } else {
        ElMessage.error(res.data.msg)
      }
    })
    .catch((e) => {
      console.log(e)
      ElMessage.error(e.response.data.msg)
    })
}
const initList = (wfList) => {
  const map = new Map()
  wfList?.forEach((v) => {
    map.set(v.id, v)
  })
  state.allSelected = map
}
onBeforeMount(() => {
  if (!route.query.haveOrNo) {
    ElMessage.error('URL地址缺少参数haveOrNo')
  }
  // ⼆级⻚⾯需要通过监听 getFormIframeData 事件，获取表单中⼼⼀级⻚⾯传递过来的数据。
  // formItem 表单项配置数据，该数据在⼆级⻚⾯回传数据给⼀级⻚⾯时需要原封不动传回 Object
  // formData 表单项填写数据 Object
  // userData ⽤户信息数据 Object
  // payload 额外的荷载数据，⼦表组件下的要素能通过此项获取到⼦表⾏数据 Object
  // apis 表单中⼼接⼝配置数据，详情可查看 ApisObject 参数说明 ApisObject
  // ApisObject.headers 接⼝请求头配置 Object
  // ApisObject.params 接⼝请求参数配置 Object
  // ApisObject.config 接⼝配置信息 Object
  window.addEventListener('message', (e) => {
    const data = e.data
    console.log('二级表单接收到的数据：', data)
    if (data.type === 'getFormIframeData') {
      const { formItem, formData, userData, apis, payload } = data.data
      state.formMessage = JSON.parse(JSON.stringify(data.data))
      state.isInit = true
      initList(formData.wfList)
    }
  })
  window.parent.postMessage(
    {
      type: 'setFormConfig',
      formHeight: 800,
    },
    '*',
  )
})
onMounted(() => {
  initDictionary()
  onReset()
})
const initDictionary = () => {}
const onConfirmIframe = (msgData) => {
  const send = {
    type: 'onConfirmIframe',
    data: JSON.parse(
      JSON.stringify({
        ...state.formMessage,
        msgData: JSON.parse(JSON.stringify(msgData)), // ⼆级⻚⾯数据
      }),
    ),
  }
  console.log('二级表单发送的数据', send)
  window.parent.postMessage(send, '*')
}
const onCloseIframe = () => {
  window.parent.postMessage(
    {
      type: 'onCloseIframe',
    },
    '*',
  )
}
</script>

<style lang="scss" scoped></style>
