<template>
  <div class="flex h-full w-full flex-col">
    <toBackCom
      title="首页"
      :rou="{
        name: '4806d051-e037-4d9d-99a0-78aa2f2f362b',
      }"
    />
    <div class="bm-main-box" style="flex-direction: row">
      <div class="flex flex-1 flex-col gap-4 overflow-hidden px-4">
        <div
          class="flex h-15 items-center text-xl font-bold text-[#2E3238]"
          style="border-bottom: var(--czr-border)"
        >
          {{ sxOnethingInfo.onething }}
        </div>
        <div class="flex h-13 items-center justify-between">
          <template v-for="(item, index) in state.step.options">
            <template v-if="index > 0">
              <div class="h-0.5 w-6 bg-[#cbced3]" />
            </template>
            <div
              class="flex items-center text-base"
              :class="`${
                item.finish || item.wait
                  ? 'font-bold text-[#2E3238]'
                  : 'text-[#A7ADB9]'
              } ${item.finish || item.wait ? '__hover' : 'cursor-no-drop'}`"
              @click="
                item.finish || item.wait
                  ? (state.step.index = index)
                  : undefined
              "
            >
              <div
                class="mr-2.5 flex size-8 items-center justify-center rounded-full border-1 border-[#A7ADB9]"
                :class="
                  item.finish || item.wait
                    ? 'border-[var(--czr-main-color)] bg-[var(--czr-main-color)] text-[#ffffff]'
                    : 'border-[#A7ADB9]'
                "
              >
                {{ index + 1 }}
              </div>
              {{ item.label }}
            </div>
          </template>
        </div>
        <template v-if="state.step.index === 0">
          <div class="flex flex-1 flex-col gap-4 overflow-hidden">
            <div class="__czr-title_2">
              {{ state.step.options[state.step.index].label }}
            </div>
            <div
              class="acceptcondition max-h-fit flex-1 overflow-y-auto rounded-sm bg-[#0062E9]/5 p-4 text-sm text-[#576275]"
              v-html="sxOnethingInfo.acceptcondition"
            />
            <div
              class="flex h-10.5 w-full items-center justify-center rounded-lg bg-[#EAF1FF] text-base text-[var(--czr-main-color)]"
              :class="
                state.step.options[state.step.index].time > 0
                  ? 'cursor-no-drop'
                  : '__hover'
              "
              @click="onStep(state.step.index)"
              v-if="!state.step.options[state.step.index].finish"
            >
              我已阅读并遵守以上规定
              <template v-if="state.step.options[state.step.index].time > 0">
                （{{ state.step.options[state.step.index].time }}s）
              </template>
            </div>
          </div>
        </template>
        <template v-else-if="state.step.index === 1">
          <div class="flex flex-1 flex-col gap-4 overflow-hidden">
            <div class="__czr-title_2">
              {{ state.step.options[state.step.index].label }}
            </div>
            <div
              class="max-h-fit flex-1 overflow-y-auto rounded-sm bg-[#0062E9]/5 p-4 text-sm text-[#576275]"
            >
              <treeNode
                :data="state.step.options[state.step.index].questions"
                ref="ref_treeNode"
                @onChange="getAnswer"
                :view="state.step.options[state.step.index].finish"
              />
            </div>
            <div
              class="flex h-10.5 w-full items-center justify-center rounded-lg text-base"
              :class="
                state.step.options[state.step.index].complete
                  ? '__hover bg-[var(--czr-main-color)] text-[#ffffff]'
                  : 'cursor-no-drop bg-[#EAF1FF] text-[var(--czr-main-color)]'
              "
              @click="onStep(state.step.index)"
              v-if="!state.step.options[state.step.index].finish"
            >
              确定
            </div>
          </div>
        </template>
        <template v-else-if="state.step.index === 2">
          <div class="flex flex-1 flex-col gap-4 overflow-hidden">
            <div class="max-h-fit flex-1 overflow-y-auto">
              <CzrForm
                ref="ref_form"
                label-width="6.1rem"
                layout="y"
                :form-view="state.step.options[state.step.index].finish"
              >
                <div class="__czr-title_2">基本信息表</div>
                <div
                  class="mt-4 grid w-full grid-cols-2 gap-x-4 rounded-sm bg-[#0062E9]/5 p-4 text-sm text-[#576275]"
                >
                  <CzrFormColumn
                    required
                    :span="24"
                    label="姓名"
                    v-model:param="
                      state.step.options[state.step.index].form.name
                    "
                    :disabled="true"
                  />
                  <CzrFormColumn
                    required
                    :span="24"
                    label="手机号码"
                    v-model:param="state.step.options[state.step.index].form.a1"
                  />
                  <CzrFormColumn
                    required
                    :span="24"
                    label="证件类型"
                    v-model:param="
                      state.step.options[state.step.index].form.certType
                    "
                    :disabled="true"
                  />
                  <CzrFormColumn
                    required
                    :span="24"
                    label="证件号码"
                    v-model:param="
                      state.step.options[state.step.index].form.certNumber
                    "
                    :disabled="true"
                  />
                  <CzrFormColumn
                    class="col-span-2"
                    required
                    :span="24"
                    label="籍贯"
                    v-model:param="state.step.options[state.step.index].form.a2"
                  />
                  <CzrFormColumn
                    class="col-span-2"
                    required
                    :span="24"
                    label="联系地址"
                    v-model:param="state.step.options[state.step.index].form.a3"
                    type="textarea"
                    :rows="2"
                  />
                </div>
                <div class="__czr-title_2 mt-4">
                  海南省灵活就业人员参保登记表
                </div>
                <div
                  class="mt-4 grid w-full grid-cols-2 gap-x-4 rounded-sm bg-[#0062E9]/5 p-4 text-sm text-[#576275]"
                >
                  <div class="col-span-2 mb-4 font-bold text-[#2E3238]">
                    基本信息
                  </div>
                  <CzrFormColumn
                    required
                    :span="24"
                    label="证件类型"
                    v-model:param="state.step.options[state.step.index].form.b1"
                    link="select"
                    :options="[
                      { label: '居民身份证（户口簿）', value: 1 },
                      { label: '中国人民解放军军官证', value: 2 },
                      { label: '中国人民武装警察警官证', value: 3 },
                      {
                        label: '香港特区护照/港澳居民来往内地通行证',
                        value: 4,
                      },
                      {
                        label: '澳门特区护照/港澳居民来往内地通行证',
                        value: 5,
                      },
                      { label: '台湾居民居住证', value: 6 },
                      { label: '外国人永久居留证', value: 7 },
                    ]"
                  />
                  <CzrFormColumn
                    required
                    :span="24"
                    label="户口所属区"
                    v-model:param="state.step.options[state.step.index].form.b2"
                  />
                  <CzrFormColumn
                    required
                    :span="24"
                    label="户口性质"
                    v-model:param="state.step.options[state.step.index].form.b3"
                    link="select"
                    :options="[
                      { label: '本省城镇', value: 1 },
                      { label: '外省城镇', value: 2 },
                      { label: '本省农村', value: 3 },
                      { label: '外省农村', value: 4 },
                      { label: '香港特别行政区居民', value: 5 },
                      { label: '澳门特别行政区居民', value: 6 },
                      { label: '台湾地区居民', value: 7 },
                    ]"
                  />
                  <CzrFormColumn
                    class="col-span-2"
                    required
                    :span="24"
                    label="户口所在地"
                    v-model:param="state.step.options[state.step.index].form.b4"
                    type="textarea"
                    :rows="2"
                  />
                  <CzrFormColumn
                    class="col-span-2"
                    required
                    :span="24"
                    label="现居住地址"
                    v-model:param="state.step.options[state.step.index].form.b5"
                    type="textarea"
                    :rows="2"
                  />
                  <CzrFormColumn
                    required
                    :span="24"
                    label="学历"
                    v-model:param="state.step.options[state.step.index].form.b6"
                    link="select"
                    :options="[
                      { label: '博士研究生', value: 1 },
                      { label: '硕士研究生', value: 2 },
                      { label: '大学本科', value: 3 },
                      { label: '大学专科', value: 4 },
                      { label: '中等专科', value: 5 },
                      { label: '职业高中', value: 6 },
                      {
                        label: '技工学校（技师班、中级工班、高级工班）',
                        value: 7,
                      },
                    ]"
                  />
                  <CzrFormColumn
                    required
                    :span="24"
                    label="国家/地区"
                    v-model:param="state.step.options[state.step.index].form.b7"
                  />
                  <div class="col-span-2 mb-4 font-bold text-[#2E3238]">
                    参保信息
                  </div>
                  <CzrFormColumn
                    required
                    :span="24"
                    label="统筹区"
                    v-model:param="state.step.options[state.step.index].form.c1"
                    link="select"
                    :options="[
                      { label: '琼海市社会保险服务中心', value: 1 },
                      { label: '万宁市社会保险服务中心', value: 2 },
                      { label: '东方市社会保险服务中心', value: 3 },
                      { label: '洋浦经济开发区社会保险服务中心', value: 4 },
                      { label: '三亚市社会保险服务中心', value: 5 },
                      { label: '五指山市社会保险服务中心', value: 6 },
                      { label: '海南省', value: 7 },
                    ]"
                  />
                  <CzrFormColumn
                    required
                    :span="24"
                    label="参保情况"
                    v-model:param="state.step.options[state.step.index].form.c2"
                    link="select"
                    :options="[
                      { label: '首次参保', value: 1 },
                      { label: '已参过保', value: 2 },
                    ]"
                  />
                  <CzrFormColumn
                    required
                    :span="24"
                    label="参保险种"
                    v-model:param="state.step.options[state.step.index].form.c3"
                    link="select"
                    :options="[
                      { label: '基本养老保险', value: 1 },
                      { label: '基本医疗保险', value: 2 },
                    ]"
                  />
                </div>
                <div class="__czr-title_2 mt-4">
                  基本养老保险、职业（企业）年金关系转移接续申请表
                </div>
                <div
                  class="mt-4 grid w-full grid-cols-2 gap-x-4 rounded-sm bg-[#0062E9]/5 p-4 text-sm text-[#576275]"
                >
                  <CzrFormColumn
                    class="col-span-2"
                    required
                    :span="24"
                    label="户籍所在地"
                    v-model:param="state.step.options[state.step.index].form.d1"
                    type="textarea"
                    :rows="2"
                  />
                  <CzrFormColumn
                    required
                    :span="24"
                    label="申请日期"
                    v-model:param="state.step.options[state.step.index].form.d2"
                    link="date"
                  />
                </div>
              </CzrForm>
            </div>
            <div
              class="__hover flex h-10.5 w-full items-center justify-center rounded-lg bg-[var(--czr-main-color)] text-base text-[#ffffff]"
              @click="onStep(state.step.index)"
              v-if="!state.step.options[state.step.index].finish"
            >
              确定
            </div>
          </div>
        </template>
        <template v-else-if="state.step.index === 3">
          <div class="__czr-title_2">
            {{ state.step.options[state.step.index].label }}
          </div>
          <div
            class="mt-4 flex w-full flex-col gap-4 rounded-sm bg-[#0062E9]/5 p-4 text-sm text-[#576275]"
          >
            <template
              v-for="(item, index) in state.step.options[state.step.index]
                .fileList"
            >
              <div class="flex items-center">
                <SvgIcon name="document" :active="true" />
                <div class="ml-1 text-sm text-[#303133]">
                  {{ item.materialname }}
                </div>
                <div
                  class="ml-2 rounded-xs border-1 border-[var(--czr-error-color)] bg-[var(--czr-error-color)]/10 px-1 py-0.5 text-[0.63rem] text-[var(--czr-error-color)]"
                >
                  {{
                    item.isneed === '1'
                      ? `必要`
                      : item.isneed === '2'
                        ? `非必要`
                        : item.isneed === '3'
                          ? `容缺后补`
                          : ``
                  }}
                </div>
                <div class="ml-auto flex items-center">
                  <template v-if="item.__isUpload">
                    <div class="flex items-center gap-1 text-xs text-[#909399]">
                      <template v-if="item.__url">
                        <SvgIcon
                          name="success"
                          color="var(--czr-success-color)"
                          size="14"
                        />已上传
                        <div class="mx-2 text-xs text-[var(--czr-main-color)]">
                          |
                        </div>
                        <SvgIcon
                          name="czr_del"
                          :active="true"
                          class="__hover"
                          @click="
                            ((item.__isUpload = false), (item.__url = ''))
                          "
                        />
                      </template>
                      <template v-else> {{ item.__process }}% </template>
                    </div>
                  </template>
                  <template v-else>
                    <a-button
                      size="small"
                      type="primary"
                      @click="onUpload(item)"
                      >上传</a-button
                    >
                  </template>
                </div>
              </div>
            </template>
          </div>
          <div
            class="flex h-10.5 w-full items-center justify-center rounded-lg text-base"
            :class="
              state.step.options[state.step.index].complete
                ? '__hover bg-[var(--czr-main-color)] text-[#ffffff]'
                : 'cursor-no-drop bg-[#EAF1FF] text-[var(--czr-main-color)]'
            "
            @click="onStep(state.step.index)"
            v-if="!state.step.options[state.step.index].finish"
          >
            下一步
          </div>
        </template>
        <template v-else-if="state.step.index === 4">
          <div class="__czr-title_2">
            {{ state.step.options[state.step.index].label }}
          </div>
          <CzrForm
            ref="ref_form"
            :form-view="state.step.options[state.step.index].finish"
          >
            <CzrFormColumn
              class="__czr-table-form-column"
              :span="24"
              label="结果领取方式"
              v-model:param="state.step.options[state.step.index].form.method"
              link="radio"
              :options="[
                { label: '邮寄', value: 1 },
                { label: '线下领取', value: 2 },
              ]"
            />
            <div
              class="w-full rounded-sm bg-[#0062E9]/5 p-4 text-sm text-[#576275]"
            >
              <div class="mb-2 text-sm text-[#2E3238]">领取地址</div>
              <CzrFormColumn
                class="__czr-table-form-column"
                required
                :span="24"
                label-width="0px"
                v-model:param="
                  state.step.options[state.step.index].form.address
                "
                type="textarea"
                :rows="4"
              />
            </div>
          </CzrForm>
          <div
            class="flex h-10.5 w-full items-center justify-center rounded-lg text-base"
            :class="
              state.step.options[state.step.index].form.address.trim()
                ? '__hover bg-[var(--czr-main-color)] text-[#ffffff]'
                : 'cursor-no-drop bg-[#EAF1FF] text-[var(--czr-main-color)]'
            "
            @click="onStep(state.step.index)"
            v-if="!state.step.options[state.step.index].finish"
          >
            提交
          </div>
        </template>
      </div>
      <div
        class="m-1 flex-1 overflow-hidden rounded-lg border-1 border-[var(--czr-main-color)]/5 shadow"
      >
        <chat :online="false" :ID="state.ID" ref="ref_chat" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  defineAsyncComponent,
  markRaw,
  nextTick,
  onMounted,
  provide,
  reactive,
  ref,
} from 'vue'
import { mockQuestion, sxOnethingInfo, sxImplBasicMaterial } from './mock'
import treeNode from './tree-node.vue'
import toBackCom from '@/views/manage/components/to-back.vue'
import { useRoute, useRouter } from 'vue-router'
import { appDetail } from '@/api/modules/app'
import chat from '@/views/chat/index.vue'
import { isValue } from '@/utils/czr-util'
import { v4 } from 'uuid'
import { fileUploadFile } from '@/api/modules/global/upload'

const route = useRoute()
const router = useRouter()
const state: any = reactive({
  ID: route.params.id,
  detail: {},
  answers: [],
  step: {
    options: [
      { label: '用户须知', finish: false, wait: true, time: 0 },
      {
        label: '情形选择',
        finish: false,
        wait: false,
        complete: false,
        questions: mockQuestion.conditionInfo,
        answers: [],
      },
      {
        label: '表单填写',
        finish: false,
        wait: false,
        form: {
          name: '张三',
          certType: '身份证',
          certNumber: '438123*********678',
        },
      },
      {
        label: '材料上传',
        finish: false,
        wait: false,
        fileList: sxImplBasicMaterial().map((v) => ({ ...v, __url: '' })),
      },
      {
        label: '结果领取',
        finish: false,
        wait: false,
        form: {
          method: 1,
          address: '',
        },
      },
    ],
    index: 4,
  },
})
const ref_chat = ref()
const ref_treeNode = ref()
const ref_form = ref()
const getAnswer = () => {
  state.step.options[state.step.index].answers = ref_treeNode.value.getAnswer()
  state.step.options[state.step.index].complete = state.step.options[
    state.step.index
  ].answers.every((a) => a.every((b) => isValue(b)))
}
const onStep = (index) => {
  const current = state.step.options[state.step.index]
  switch (state.step.index) {
    case 0:
      {
        if (!current.finish) {
          current.finish = true
          current.wait = false
          state.step.options[index + 1].wait = true
          ref_chat.value.mockAnswer({
            text: '欢迎进入事项网办阶段！请选择情形',
          })
        }
        state.step.index = index + 1
      }
      break
    case 1:
      {
        if (current.complete) {
          if (!current.finish) {
            current.finish = true
            current.wait = false
            state.step.options[index + 1].wait = true
            const id = v4()
            const ddd = () => {
              console.log(123123)
            }
            ref_chat.value.mockAnswer({
              text: '欢迎进入表单填写阶段！为了让您的体验更加顺畅，我已经贴心地为您预先填写了部分内容。接下来，请在左侧补充剩余的信息，感谢您的配合！',
              teleport: id,
              com: {
                is: defineAsyncComponent(
                  () =>
                    import(
                      '@/views/business/doing-with-chat/chat/form-list.vue'
                    ),
                ),
                binds: {
                  data: ['asdasd', 'zxvzxvzxv'],
                  ddd,
                },
              },
            })
            // state.components.push({
            //   id,
            //   is: defineAsyncComponent(
            //     () =>
            //       import(
            //         '@/views/business/doing-with-chat/chat/form-list.vue'
            //         ),
            //   ),
            //   props: {
            //     data: ['asdasda', 'faszxcszczxc'],
            //   },
            // })
          }
          state.step.index = index + 1
        }
      }
      break
    case 2:
      {
        // ref_form.value.submit().then(() => {
        if (!current.finish) {
          current.finish = true
          current.wait = false
          state.step.options[index + 1].wait = true
          ref_chat.value.mockAnswer({
            text: '表单已填写完成！接下来进入材料上传阶段！以下是需要您提供的材料，请在左侧上传',
          })
        }
        state.step.index = index + 1
        // })
      }
      break
    case 3:
      {
        if (!current.finish) {
          current.finish = true
          current.wait = false
          state.step.options[index + 1].wait = true
          ref_chat.value.mockAnswer({
            text: '请填写结果材料领取方式',
          })
        }
        state.step.index = index + 1
      }
      break
    case 4:
      {
        ref_form.value.submit().then(() => {
          if (!current.finish) {
            current.finish = true
            current.wait = false
            ref_chat.value.mockAnswer({
              text: '办理成功！该事项将在8个工作日内办结，请耐心等待',
            })
          }
        })
      }
      break
  }
}
const onUpload = (row) => {
  const oldInput = document.getElementById('fileInput')
  if (oldInput) {
    oldInput.remove()
  }
  const fileInput = document.createElement('input')
  fileInput.type = 'file'
  fileInput.id = 'fileInput'
  fileInput.style.display = 'none'
  document.body.appendChild(fileInput)
  fileInput.addEventListener('change', (e: any) => {
    const file = e.target.files[0]
    if (file) {
      const formData = new FormData()
      formData.append('file', file)
      row.__isUpload = true
      fileUploadFile(formData, (process) => {
        row.__process = process
      })
        .then(({ data }: any) => {
          row.__url = data.path
          if (
            state.step.options[state.step.index].fileList.every((v) => v.__url)
          ) {
            state.step.options[state.step.index].complete = true
            ref_chat.value.mockAnswer({
              text: '检测到您已上传必要材料，请再次核对，上传完成无误后点击下一步',
            })
          }
        })
        .catch(() => {})
        .finally(() => {})
    }
  })
  fileInput.click()
}

onMounted(() => {
  initDetail()
  console.log(sxImplBasicMaterial())
})
const initDetail = () => {
  if (state.ID) {
    appDetail(state.ID)
      .then(({ data }: any) => {
        state.detail = data
        document.title = state.detail.name
        nextTick(() => {
          ref_chat.value?.init()
          const timer = setInterval(() => {
            state.step.options[0].time -= 1
            if (state.step.options[0].time === 0) {
              clearInterval(timer)
            }
          }, 1000)
        })
      })
      .catch(() => {
        router.push({ name: '4806d051-e037-4d9d-99a0-78aa2f2f362b' })
      })
  } else {
    router.push({ name: '4806d051-e037-4d9d-99a0-78aa2f2f362b' })
  }
}
</script>

<style lang="scss" scoped>
.acceptcondition > * {
  line-height: 1.5rem;
}
</style>
