import {
  ref,
  defineComponent,
  computed,
  onMounted,
  onUnmounted,
  reactive,
} from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { upload, UploadData } from '@/api/common';
import cloneDeep from 'lodash/cloneDeep';
import div from '@/components/div';
import { useCommonStore, useIncidentStore } from '@/store';
import QueryMap from '@/components/QueryMap';
import { BaseMediaUrl} from '@/utils/index';
// import MediaUpload from '@/components/MediaUpload';
import './index.scss';
import {
  DropdownItemOption,
  NavBar,
  DropdownMenu,
  DropdownItem,
  Icon,
  PullRefresh,
  Sticky,
  Collapse,
  CollapseItem,
  Loading,
  Form,
  Field,
  CellGroup,
  Popup,
  Picker,
  ActionBar,
  Button,
  Notify,
  Uploader,
  UploaderFileListItem,
} from 'vant';
import { isArray } from 'lodash';

export default defineComponent({
  name: 'IncidentManagementReport',
  setup() {
    const store = useIncidentStore();
    const commonStore = useCommonStore();
    const detail = computed(() => store.incidentDetail?.baseInfo);
    const addr = ref('');

    const form = ref({ ...detail.value });
    const formRef = ref();

    const showCreateByPicker = ref(false);

    const showCreateTypeByPicker = ref(false);

    const route = useRoute();
    const router = useRouter();
    const isshowprew = ref(false);
    const videosrclist = reactive([]);
    const imagessrclist = reactive([]);
    const videop = ref();
    const videopsrc = ref("");

    const handleUpload = (file) => {
      upload(file).then((res) => { 
        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)=>{ 

      });
    };

    const handleSaveReport = () => {
      const { id } = route.query;

      const saveFn = id ? store.putIncidentItem : store.postIncidentItem;
      // console.log(formRef);

      const result = saveFn({
        ...form.value,
        level: Number(form.value.level) ?? null,
        type: Number(form.value.type) ?? null,
        pic: imagessrclist.map((i: UploadData) => i.url).join(','),
        video: videosrclist.map((i: UploadData) => i.url).join(','),
        // status: route.params.status as unknown as number,
      });

    };

    onMounted(async () => {
      commonStore.getGlobalDict('zhdd_incident_level');
      commonStore.getGlobalDict('zhdd_incident_type');
      commonStore.getGlobalDict('zhdd_org_upload');

      route.query.id && (await store.getIncidentItem(route.query.id as string));
      addr.value = detail?.value?.addr ?? '';
      if (detail.value) {
        form.value = cloneDeep(detail.value);
      }
    });

    onUnmounted(() => {
      commonStore.uploadFiles = [];
      store.incidentDetail = {};
      store.incidentDetail = {
        baseInfo: {},
        process: [],
        task: [],
      };
    });

    return () => (
      <div class="incident-report-container ">
        <NavBar
          title="应急处置"
          left-arrow
          fixed
          onClick-left={() => router.push('/home')}
        />
        <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>
        <Form>
          <CellGroup>
            <Field
              v-model={form.value.name}
              name="事件标题"
              label="事件标题"
              placeholder="请输入"
              required
              rules={[{ required: true, message: '事件标题必填' }]}
            />
            <Field
              v-model={form.value.createBy}
              name="上报人"
              label="上报人"
              placeholder="请输入"
              required
              rules={[{ required: true, message: '上报人必填' }]}
            />
            <Field
              v-model={form.value.createDept}
              name="上报单位"
              label="上报单位"
              placeholder="请输入"
              required
              rules={[{ required: true, message: '上报单位必填' }]}
            />
            <Field
              v-model={form.value.typeText}
              is-link
              readonly
              name="事件类型"
              label="事件类型"
              placeholder="请选择"
              required
              rules={[{ required: true, message: '事件类型必填' }]}
              onClick={() => (showCreateTypeByPicker.value = true)}
            />
            <Popup
              v-model:show={showCreateTypeByPicker.value}
              position="bottom">
              <Picker
                columns={commonStore.globalDict['zhdd_incident_type']?.map(
                  (i) => ({ text: i.dictLabel, value: i.dictValue }),
                )}
                onConfirm={(value) => {
                  form.value.typeText = value.text;
                  form.value.type = value.value;
                  console.log(value, '---');

                  showCreateTypeByPicker.value = false;
                }}
                onCancel={() => {
                  showCreateTypeByPicker.value = false;
                }}
              />
            </Popup>
            <Field
              v-model={form.value.levelText}
              is-link
              readonly
              name="事件等级"
              label="事件等级"
              placeholder="请选择"
              required
              rules={[{ required: true, message: '事件等级必填' }]}
              onClick={() => (showCreateByPicker.value = true)}
            />
            <Popup v-model:show={showCreateByPicker.value} position="bottom">
              <Picker
                columns={commonStore.globalDict['zhdd_incident_level']?.map(
                  (i) => ({ text: i.dictLabel, value: i.dictValue }),
                )}
                onConfirm={(value) => {
                  form.value.levelText = value.text;
                  form.value.level = value.value;
                  console.log(value, '---');

                  showCreateByPicker.value = false;
                }}
                onCancel={() => {
                  showCreateByPicker.value = false;
                }}
              />
            </Popup>
            <Field
              v-model={form.value.des}
              rows={2}
              autosize
              name="事件描述"
              label="事件描述"
              type="textarea"
              placeholder="请输入"
            />
            <Field
              v-model={form.value.addr}
              name="事件地点"
              label="事件地点"
              placeholder="请输入"
              required
              onChange={(add: string) => {
                addr.value = add.target.value;
              }}
              rules={[{ required: true, message: '事件地点必填' }]}
            />
            <QueryMap
              address={addr.value}
              v-model:locations={form.value.locations}
              v-model:longitude={(form.value.locations ?? '').split(',')[0]}
              v-model:latitude={(form.value.locations ?? '').split(',')[1]}
              onChoose={(name) => {
                form.value.addr = name;
              }}
              onRestPositon={() => {
                addr.value = store.incidentDetail.baseInfo?.addr ?? '';
                form.value.addr = store.incidentDetail.baseInfo?.addr;
                form.value.locations = store.incidentDetail.baseInfo?.locations;
              }}
            />
            <Field
              name="上传视频"
              label="上传视频"
              placeholder="请输入"
              v-slots={{
                input: () => (
                  <Uploader
                    accept="video/*"
                    v-model={form.value.video}
                    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) {}
                    }}

                    // v-slots={{
                    //   'preview-cover': () => (
                    // <video
                    // style="width:100%;height:100%"
                    // controls
                    // src="https://vod-progressive.akamaized.net/exp=1643032410~acl=%2Fvimeo-prod-skyfire-std-us%2F01%2F2673%2F7%2F188365455%2F623960082.mp4~hmac=e4a0fb352e805ff4fe74317441bf6f6deb059508cc7bb2f7aa92884023b13818/vimeo-prod-skyfire-std-us/01/2673/7/188365455/623960082.mp4?filename=Emoji+Saver+-+Drama.mp4"></video>
                    // ),
                    // }}
                  />
                ),
              }}
            />
            <Field
              name="上传图片"
              label="上传图片"
              placeholder="请输入"
              v-slots={{
                input: () => (
                  <Uploader
                    accept="image/*"
                    v-model={form.value.pic}
                    onDelete={(filep, detail) => {
                      imagessrclist.splice(detail.index, 1);
                      console.log(imagessrclist);
                    }}
                    afterRead={(
                      file: UploaderFileListItem | UploaderFileListItem[],
                    ) => {
                      handleUpload((isArray(file) ? file[0] : file).file);
                      return false;
                    }}
                  />
                ),
              }}
            />
          </CellGroup>
          <div style={{ height: '80px' }}></div>

          <ActionBar>
            <div style={{ padding: '10px 20px' }}>
              <Button block type="primary" onClick={handleSaveReport}>
                提交
              </Button>
            </div>
          </ActionBar>
        </Form>
      </div>
    );
  },
});
