import {
  ref,
  defineComponent,
  onMounted,
  computed,
  onUnmounted,
  reactive,
  watch,
} from 'vue';
import { useRouter, useRoute } from 'vue-router';
import './index.scss';
import { upload, UploadData } from '@/api/common';
import { isArray } from 'lodash';
import { useCommonStore, useIncidentStore } from '@/store';
import { BaseMediaUrl, isImage, isVideo } from '@/utils';
import {
  DropdownItemOption,
  NavBar,
  DropdownMenu,
  DropdownItem,
  Icon,
  PullRefresh,
  Sticky,
  Collapse,
  CollapseItem,
  Field,
  Button,
  Loading,
  Toast,
  Step,
  Steps,
  Dialog,
  Popup,
  Uploader,
  UploaderFileListItem,
  ImagePreview,
} from 'vant';
/** @ts-ignore */
import icon_communication from '@/assets/icons/incident/communication@2x.png';
/** @ts-ignore */
import icon_detail from '@/assets/icons/incident/detail@2x.png';
/** @ts-ignore */
import icon_information from '@/assets/icons/incident/information@2x.png';
/** @ts-ignore */
import icon_plan from '@/assets/icons/incident/plan@2x.png';
/** @ts-ignore */
import icon_yjck from '@/assets/icons/incident/yjck@2x.png';
/** @ts-ignore */
import icon_yjya from '@/assets/icons/incident/yjya@2x.png';

/** @ts-ignore */
import icon_video from '@/assets/icons/incident/video.png';

;
import { cloneDeep, take } from 'lodash';



export default defineComponent({
  name: 'IncidentManagementDetail',
  setup() {
    const router = useRouter();

    const route = useRoute();

    const store = useIncidentStore();

    const commonStore = useCommonStore();

    const activeNames = ref([
      '事件信息',
      '应急预案',
      '处置方案',
      '处置详情',
      '融合通信',
    ]);
    const activeoplanNames = ref([
      
    ]);
    const message = ref('');
    const dosubmitdata = () => { 
      if (!store.incidentDetail.baseInfo?.id || message.value == "") {
        Toast.fail('信息不完整');
      }
        store
          .addIncidentProcess({
            incidentId: store.incidentDetail.baseInfo?.id,
            des: message.value,
            taskId: currenttaskid.value,
            video: videosrclist.map((i: UploadData) => i.url).join(','),
            pic: imagessrclist.map((i: UploadData) => i.url).join(','),
          })
          .then(() => {
            message.value = '';
            videosrclist.splice(0);
            imagessrclist.splice(0);
            form.value = { pic: [], video: [] };
            store.getIncidentItem(store.incidentDetail.baseInfo?.id ?? '');
          });
      
      
    };

    const dohs = () => { 
      try {
         
        uni.postMessage({
          data: {
            type: 'RHTX_gotoMeetMember',
            data: 'yjzh',
          },
        });

      } catch (E) { 
      }
     
    }

    const planOptions = computed(
      () =>
        Object.keys(store.incidentDetail?.baseTask ?? {})
          .map((idx) => {
            const item = commonStore.globalDict['zhdd_incident_level']?.find(
              (i) =>
                i.dictValue ===
                store.incidentDetail?.baseTask?.[idx]?.[0].level?.toString(),
            );
            const desc = store.incidentDetail?.baseTask?.[idx]?.map(
              (i) => i.taskDes,
            );

            return {
              ...item,
              desc,
            };
          })
          ?.find(
            (item) =>
              item.dictValue?.toString() ===
              store.incidentDetail?.baseInfo?.level?.toString(),
          )?.desc,
    );

    const currenttaskid = ref('');

    const process = ref([]);
    const handleUpload = (file) => {
      Toast.loading({
        message: '上传中...',
        duration: 0,
        forbidClick: true,
      });
      upload(file)
        .then((res) => {
          Toast.clear();
          let type = /\w+([.jpg|.png|.gif|.swf|.bmp|.jpeg]){1}$/.test(
            res.data.fileName?.substr(
              res.data.fileName?.lastIndexOf('.') + 1,
            ) ?? '',
          );
          if (!type) {
            videosrclist.push(res.data);
          } else {
            imagessrclist.push(res.data);
          }
        })
        .catch((error) => {
          Toast.clear();
        });
    };

    watch(
      () => store.incidentDetail.process,
      () => {
        var mkdtemp = {};
        store.incidentDetail.process?.map((i) => {
          var list = mkdtemp[i.taskId] ?? [];
          list.push(i);
          mkdtemp[i.taskId] = list;
        });
         console.log(mkdtemp);
        process.value = [];
        store.incidentDetail.process?.map((i) => {
          var list = cloneDeep(mkdtemp[i.taskId] ?? []);
          if (i.taskId && list.length > 0 && list[0].id === i.id) {
            list.splice(0, 1);
            process.value.push({
              ...i,
              child: list,
            });
          } else {
            if (!i.taskId) {
              process.value.push({
                ...i,
              });
            }
          }
        });

      },
    );

    const form = ref({pic:[],video:[]});
     const videosrclist = reactive([]);
     const imagessrclist = reactive([]);
     const videop = ref();
    const videopsrc = ref('');
    const isshowprew = ref(false);
    onMounted(() => {
      commonStore.getGlobalDict('zhdd_incident_level');
      commonStore.getGlobalDict('zhdd_incident_type');
      commonStore.getGlobalDict('zhdd_incident_source');

      route.query.id && store.getIncidentItem(route.query.id as string);

      if (route.query.taskid) { 
         currenttaskid.value = route.query.taskid as string; 
      } 
    });

    const getisbj = () => { 
      if (currenttaskid.value == "")
        return true;
      var isok = false;
      store.incidentDetail.task?.map(ii => {
        if (ii.id == currenttaskid.value && ii.backLogFlag == "1") {
          isok = true;
        }
      })
      return isok;
    }

    onUnmounted(() => {
      store.incidentDetail = {};
    });

    return () => (
      <div class="incident-detail-container">
        <NavBar
          title="应急处置"
          left-arrow
          fixed
          onClick-left={() => {
            try {
              uni.navigateBack();
            } catch (E) {}
            //window.history.back();
          }}
        />
        <Sticky offsetTop={'46px'}>
          <div class="title">{store.incidentDetail?.baseInfo?.name}</div>
        </Sticky>
        <Popup
          style="width:100%;background:rgba(0,0,0,0)"
          v-model:show={isshowprew.value}
          onClose={() => {
            videop.value.pause();
          }}>
          <video
            ref={videop}
            src={videopsrc.value}
            controls
            autoplay="true"
            style="width:100%"></video>
        </Popup>
        <Collapse v-model={activeNames.value}>
          <CollapseItem
            title="处置方案"
            name="处置方案"
            v-slots={{ icon: <img class="icon-i" src={icon_plan} /> }}>
            {/* <Collapse v-model={activeoplanNames.value}> */}
            <div style={'color:#333'}>
              {store.incidentDetail.task
                ?.filter((i) => i.id == route.query.taskid)
                .map((i) => (
                  <>
                    <div>{i.taskName}</div>
                    <div
                      style={`color:#000;font-size:10px;font-weight:600;padding:6px 0;${
                        i.chemicals != '' && i.chemicals != null
                          ? ''
                          : 'display:none'
                      }`}>
                      危化品：
                      {i.chemicalsText?.split(',').map((tt, indx) => (
                        <span
                          style={'color:#0B33A8;margin-right:10px'}
                          onClick={() => {
                            //查找id
                            var idc = i.chemicals?.split(',')[indx];
                            router.push(`/chemical/detail?id=${idc}`);
                          }}>
                          {tt}
                        </span>
                      ))}
                    </div>
                  </>
                ))}

              <div style={getisbj() ? 'display:none' : ''}>
                <div style={'padding:8px 0'}>
                  <span style={'color:red'}>*</span>反馈内容
                </div>
                <Field
                  v-model={message.value}
                  autosize
                  class={'textarea'}
                  type="textarea"
                  placeholder="请输入"
                />
                <div style={'height:13px;width:1px'}></div>
                <Field
                  class={'uploadc'}
                  v-slots={{
                    input: () => (
                      <Uploader
                        accept="image/*"
                        v-model={form.value.pic}
                        max-size={20 * 1024 * 1024}
                        onOversize={() => {
                          Toast('最大支持20M的图片');
                        }}
                        onDelete={(filep, detail) => {
                          imagessrclist.splice(detail.index, 1);
                          console.log(imagessrclist);
                        }}
                        afterRead={(
                          file: UploaderFileListItem | UploaderFileListItem[],
                        ) => {
                          handleUpload((isArray(file) ? file[0] : file).file);
                          return false;
                        }}
                      />
                    ),
                  }}
                />

                <Field
                  class={'uploadc'}
                  v-slots={{
                    input: () => (
                      <Uploader
                        accept="video/*"
                        v-model={form.value.video}
                        upload-icon={'video-o'}
                        max-size={100 * 1024 * 1024}
                        onOversize={() => {
                          Toast('最大支持100M的视屏');
                        }}
                        afterRead={(
                          file: UploaderFileListItem | UploaderFileListItem[],
                        ) => {
                          handleUpload((isArray(file) ? file[0] : file).file);
                          return false;
                        }}
                        onDelete={(filep, detail) => {
                          videosrclist.splice(detail.index, 1);
                          console.log(videosrclist);
                        }}
                        onClick-preview={(index) => {
                          isshowprew.value = true;
                          try {
                            videopsrc.value = URL.createObjectURL(index.file);
                            videop.value.play();
                            videop.value.currentTime = 0;
                          } catch (error) {}
                        }}
                      />
                    ),
                  }}
                />
                <div class="cz-action">
                  <Button
                    size="small"
                    type="primary"
                    onClick={() => {
                      dosubmitdata();
                    }}>
                    保存
                  </Button>
                  <Button
                    size="small"
                    type="default"
                    onClick={() => {
                      message.value = '';
                      form.value = { pic: [], video: [] };
                    }}>
                    取消
                  </Button>
                  <Button
                    color="red"
                    style={getisbj() ? 'display:none' : ''}
                    size="small"
                    type="default"
                    onClick={() => {
                      if (getisbj()) {
                        return;
                      }
                      Dialog.confirm({
                        title: '提示',
                        confirmButtonText: '办结',
                        message:
                          '点击办结按钮后，将无法继续反馈，请确认好是否完成！',
                      })
                        .then(() => {
                          // on confirm
                          store.putbackLog(currenttaskid.value);
                          try {
                            uni.navigateBack();
                          } catch (E) {}
                        })
                        .catch(() => {
                          // on cancel
                        });
                    }}>
                    办结
                  </Button>
                </div>
              </div>
            </div>

            {/* </Collapse> */}
          </CollapseItem>
          <CollapseItem
            title="处置详情"
            name="处置详情"
            v-slots={{ icon: <img class="icon-i" src={icon_detail} /> }}>
            <div>
              {process.value
                ?.filter((i) => i.taskId === currenttaskid.value)
                .map((i, index) => (
                  <div class="czxq-item">
                    <div class="cz-yuan"></div>
                    <div
                      class="cz-line"
                      style={`display:${
                        index ==
                        (process.value?.filter(
                          (i) => i.taskId === currenttaskid.value,
                        )?.length ?? 0) -
                          1
                          ? 'none'
                          : 'block'
                      }`}></div>
                    <div class="cz-time"> {i.createTime}</div>
                    <div class="cz-des">
                      {' '}
                      {i.des}
                      <div
                        style={`margin-top: 4px;${
                          (i.child ?? []).length > 0 ? '' : 'display:none'
                        }`}
                        class={i.taskId == currenttaskid.value ? 'active' : ''}>
                        {(i.child ?? [])?.map((ii, index) => (
                          <div class="czxq-item">
                            <div class="cz-yuan"></div>
                            <div
                              class="cz-line"
                              style={`display:${
                                index == ((i.child ?? [])?.length ?? 0) - 1
                                  ? 'none'
                                  : 'block'
                              }`}></div>
                            <div class="cz-time"> {ii.createTime}</div>
                            <div class="cz-des">
                              <div style={'margin-bottom:8px'}>{ii.des}</div>

                              <div
                                class={'img'}
                                style={
                                  ii.pic === '' && ii.video === ''
                                    ? 'display:none'
                                    : ''
                                }>
                                {((ii.pic ?? '') + ',' + (ii.video ?? '') ?? '')
                                  .split(',')
                                  .map((iim, idxq) => {
                                    iim = iim ?? '';
                                    if (isImage({ fileName: iim, url: iim })) {
                                      // console.log(iim);
                                      return (
                                        <img
                                          src={BaseMediaUrl + iim}
                                          onClick={() => {
                                            ImagePreview({
                                              images: ii.pic
                                                .split(',')
                                                .filter((cc) => cc != '')
                                                .map((cc) => {
                                                  return BaseMediaUrl + cc;
                                                }),
                                              startPosition: idxq,
                                            });
                                          }}
                                          style={
                                            'width:20px;height:30px;object-fit: contain;margin-right:10px;padding:0 10px;background:rgb(240 236 236);'
                                          }></img>
                                      );
                                    }
                                    if (isVideo({ fileName: iim, url: iim })) {
                                      // console.log(iim);
                                      return (
                                        <img
                                          onClick={() => {
                                            isshowprew.value = true;
                                            try {
                                              videopsrc.value =
                                                BaseMediaUrl + iim;
                                              videop.value.play();
                                              videop.value.currentTime = 0;
                                            } catch (error) {}
                                          }}
                                          src={icon_video}
                                          style={
                                            'width:20px;height:30px;object-fit: contain;margin-right:10px;background:rgb(240 236 236);padding:0 10px;border-radius:4px'
                                          }></img>
                                      );
                                    }
                                    return <div></div>;
                                  })}
                              </div>
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  </div>
                ))}
              <div onClick={() => { 
                if (route.query.taskid) {
                  router.push(
                    `/status/${route.params.status}/detail?id=${route.query.id}&taskid=${route.query.taskid}`,
                  );
                } else { 
                  router.push(
                    `/status/${route.params.status}/detail?id=${route.query.id}`,
                  );
                }
              }}
                style={
                  'padding-bottom: 30px; text-align: right; padding-top: 10px;padding-top:10px;color:#0B33A8'
                }>
                查看详情
              </div>
            </div>
          </CollapseItem>
        </Collapse>
      </div>
    );
  },
});
