<template>
  <div class="interpret-box">
    <div class="interpret-form">
      <a-form
        ref="formRef"
        :rules="data.rules"
        :model="ruleForm"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-item label="案件编号">
          <a-input v-model:value="ruleForm.case_no" disabled />
        </a-form-item>
        <a-form-item label="案件详情">
          <a-input v-model:value="ruleForm.case_description" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="违规类型" name="typeid">
          <a-select
            v-model:value="ruleForm.typeid"
            placeholder="请选择"
            :options="data.violationOptions"
            :field-names="{ label: 'itemName', value: 'itemValue' }"
          />
        </a-form-item>
        <a-form-item label="图斑面积">
          <a-input v-model:value="ruleForm.area" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="县/区">
          <a-select
            v-model:value="ruleForm.countyid"
            placeholder="请选择"
            :options="data.cityDatas"
            :field-names="{ label: 'itemName', value: 'itemValue' }"
          />
        </a-form-item>
        <a-form-item label="乡镇/街道">
          <a-select
            v-model:value="ruleForm.streetid"
            placeholder="请选择"
            :options="data.streetDatas"
            :field-names="{ label: 'itemName', value: 'itemValue' }"
          />
        </a-form-item>
        <a-form-item label="社区/村">
          <a-select
            v-model:value="ruleForm.communityname"
            placeholder="请选择"
            :options="data.communtDatas"
            :field-names="{ label: 'itemName', value: 'itemValue' }"
          />
        </a-form-item>
        <a-form-item label="详细地址">
          <a-input v-model:value="ruleForm.address" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="备注">
          <a-textarea
            v-model:value="ruleForm.description"
            placeholder="备注"
            :auto-size="{ minRows: 1, maxRows: 3 }"
          />
        </a-form-item>
        <a-form-item label="现场照片">
          <ImagePreview :imageList="picListData" />
          <ImageUpload
            file-list="fileList"
            :maxSize="20"
            :maxNumber="10"
            :api="imgApi"
            :multiple="true"
            @delete="handleRemove"
          />
        </a-form-item>
      </a-form>
    </div>
    <div class="btn-box">
      <a-button color="info" class="ml-2" @click="resetForm">取消</a-button>
      <a-button color="info" class="ml-2" type="primary" @click="saveForm">保存</a-button>
      <a-button color="success" class="ml-2" type="primary" @click="submitForm">提交</a-button>
      <a-button color="info" class="ml-2" type="primary" danger @click="eventClose">关闭</a-button>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { ImageUpload } from '@/components/Upload';
  import { ref, reactive, watch, onMounted } from 'vue';
  import { ImagePreview } from '@/components/Preview';
  import { getCaseInfo, addDroneCaseInfo, updateDroneCaseInfoIntact } from '@/api/monitor/index';
  import { getLoadCaseType } from '@/api/sys/sysDataItemDetail';
  import { uploadApi } from '@/api/sys/upload';
  // 图片服务器地址
  import { useGlobSetting } from '@/hooks/setting';
  import { useMessage } from '@/hooks/web/useMessage';
  //引入turf.js
  import * as turf from '@turf/turf';

  interface ruleFormObj {
    case_no?: string;
    case_description?: string;
    typeid?: string;
    area?: string;
    countyid?: string;
    streetid?: string;
    communityname?: string;
    address?: string;
    description?: string;
    id?: string;
    is_intact?: number;
  }
  const { createMessage, createConfirm } = useMessage();
  const { uploadUrl } = useGlobSetting();
  const emit = defineEmits(['close']);
  const formRef = ref();
  const labelCol = { span: 7 };
  const wrapperCol = { span: 17 };
  const ruleForm = ref<ruleFormObj>({});
  const fileList: any = ref([]);
  const filSuccessList: any = ref([]);
  const formData: any = ref({});
  const picListData: any = ref([]);
  const abbreviationPicListData: any = ref([]);
  const data = reactive({
    violationOptions: [],
    communtDatas: [],
    streetDatas: [],
    cityDatas: [],
    rules: {
      typeid: [{ required: true, message: '请选择违规类型' }],
    },
  });
  watch(fileList, (newValue) => {
    // 监听 fileList 的变化
    // newValue 的值就是 formUser 的真实值 === formUser.value
    console.log(newValue);
  });
  const props = defineProps({
    interpretData: {
      type: Object,
      default: () => {
        return {};
      },
    },
  });
  ruleForm.value = props.interpretData;
  watch(
    () => props.interpretData,
    (newVal) => {
      ruleForm.value = newVal;
      getFormData();
    },
  );
  onMounted(() => {
    getFormData();
    getNoBuildStatus();
  });

  // 获取现场照片
  async function getFormData() {
    picListData.value = [];
    const data: any = await getCaseInfo({ id: ruleForm.value.id });
    formData.value = data;
    data.pics.forEach((item) => {
      picListData.value.push(uploadUrl + '/' + item.path);
      // 缩略图
      abbreviationPicListData.value.push(uploadUrl + '/S_' + item.path);
    });
  }
  async function imgApi(file, progress) {
    const data: any = await uploadApi(file, progress);
    if (data.result.length > 0) {
      fileList.value.push(file);
      filSuccessList.value.push(data.data.result[0]);
    }
  }
  function handleRemove(file) {
    console.log(file);
    var currentIndex = (fileList.value || []).findIndex((element) => element.uid === file.uid);
    fileList.value.splice(currentIndex, 1);
    filSuccessList.value.splice(currentIndex, 1);
  }
  //   获取违规类型
  async function getNoBuildStatus() {
    const obj = await getLoadCaseType();
    data.violationOptions = obj;
  }
  // 获取地区
  // async function getAreasData() {
  //   getMethodCommon('/Orgs/LoadOrgList', { name: '费县' }).then((res) => {
  //     this.areasDatas = res.result;
  //     res.result.forEach((item) => {
  //       if (item.parentName == '临沂市') {
  //         this.cityDatas.push(item);
  //       }
  //       if (item.parentId == this.ruleForm.countyid) {
  //         this.streetDatas.push(item);
  //       }
  //       if (item.parentId == this.ruleForm.streetid) {
  //         this.communtDatas.push(item);
  //       }
  //     });
  //   });
  // }
  // 表单验证
  async function validateForm() {
    let res = await formRef.value
      .validate()
      .then(() => {
        return true;
      })
      .catch(() => {
        return false;
      });
    return res;
  }
  // 取消
  function resetForm() {
    emit('close');
  }

  // 保存
  async function saveForm() {
    formData.value.info = ruleForm.value;
    filSuccessList.value.forEach((element) => {
      formData.value.pic_list.push(element.filePath);
    });
    console.log(formData.value);
    const data = await addDroneCaseInfo(formData.value);
    if (data) {
      resetForm();
      return createMessage.success('成功');
    } else {
      return createMessage.error('失败');
    }
  }
  // 提交
  async function submitForm() {
    const success = await validateForm();
    console.log(success);
    if (!success) {
      return;
    }
    formData.value.info = ruleForm.value;
    formData.value.info.is_intact = 1;
    filSuccessList.value.forEach((element) => {
      formData.value.pic_list.push(element.filePath);
    });
    console.log(formData.value);
    const data = await updateDroneCaseInfoIntact(formData.value);
    if (data) {
      resetForm();
      return createMessage.success('成功');
    } else {
      return createMessage.error('失败');
    }
  }
  // 关闭
  async function eventClose() {
    createConfirm({
      iconType: 'warning',
      title: '关闭',
      content: '确认关闭此案件?',
      onOk: async () => {
        const data = await closeDroneCaseInfo({ id: ruleForm.value.id });
        if (data) {
          return createMessage.success('成功');
        } else {
          return createMessage.error('失败');
        }
      },
    });
  }
  function setMap(data) {
    let area = 0;

    let coordinates: any = [];
    data.forEach((item) => {
      console.log([item.lng, item.lat]);
      coordinates.push([item.lng, item.lat]);
    });
    let polygons = turf.polygon([coordinates]);
    area = turf.area(polygons);
    console.log(area);
    ruleForm.value.area = area.toFixed(2);
  }
  defineExpose({
    setMap,
  });
</script>
<style lang="less" scoped>
  .interpret-box {
    width: 100%;
    height: 74vh;
    position: relative;
    .interpret-form {
      overflow-y: auto;
      height: 100%;
      padding-bottom: 20px;
    }
    .ant-form {
      padding: 20px;
      display: flex;
      flex-direction: column;
      .ant-form-item {
        float: left;
        margin-bottom: 10px;
        margin-left: 4px;
        width: 100%;
        button {
          margin-right: 10px;
        }
      }
    }
    ::v-deep .ant-image-img {
      width: 50%;
    }
  }
  ::v-deep .ant-image .ant-image-img {
    width: 100px;
    margin-bottom: 10px;
  }
  .btn-box {
    width: 100%;
    padding: 10px 10%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    bottom: 0px;
    left: 0;
    background-color: @component-background;
  }
</style>
