<template>
<a-spin :spinning="props.modalLoading">
  <div class="modal-content">
    <div class="row">
      <div class="item">
        <div class="label">图斑编号：</div>
        <div class="item-value" style="flex:2">
          <a-input v-model:value="props.infoData.case_no" :disabled="!props.control"/>
        </div>
      </div>
      <div class="item">
        <div class="label">图斑类型：</div>
        <div class="item-value">
          <a-select 
            style="width: 100%"
            v-model:value="props.infoData.typename"
            :options="typenameOptions"
            placeholder="请选择图斑类型"
            :disabled="!props.control"/>
        </div>
      </div>
      <div class="item" style="flex:2">
        <div class="label">图斑详情：</div>
        <div class="item-value" style="flex:3">
          <a-select 
            v-if="props.type == '违法用地'"
            style="width: 50%"
            v-model:value="caseDescription[0]"
            :options="tubanbiaoqian1Options"
            placeholder="请选择图斑详情"
            :disabled="!props.control"/>
          <a-select 
            v-if="props.type == '违法用地'"
            style="width: 50%"
            v-model:value="caseDescription[1]"
            :options="tubanbiaoqian2Options"
            placeholder="请选择图斑详情"
            :disabled="!props.control"/>
          <a-input v-else v-model:value="props.infoData.case_description"
          :disabled="!props.control"/>
        </div>
      </div>
    </div>
    <div class="row">
      <div class="item">
        <div class="label">县/区：</div>
        <div class="item-value">
          <a-select
            style="width: 100%"
            v-model:value="props.infoData.countyid"
            :options="countyOptions"
            @change="handleCountyChange"
            placeholder="请选择县/区"
            :disabled="!props.control"/>
        </div>
      </div>
      <div class="item">
        <div class="label">乡镇/街道：</div>
        <div class="item-value">
          <a-select
            style="width: 100%"
            v-model:value="props.infoData.streetid"
            :options="streetOptions"
            @change="handleStreetChange"
            placeholder="请选择乡镇/街道"
            :disabled="!props.control"/>
        </div>
      </div>
      <div class="item">
        <div class="label">社区/村：</div>
        <div class="item-value">
          <a-select
            style="width: 100%"
            v-model:value="props.infoData.communityid"
            :options="communityOptions"
            @change="handleCommunityChange"
            placeholder="请选择社区/村"
            :disabled="!props.control"/>
        </div>
      </div>
      <div class="item">
        <div class="label">详细地址：</div>
        <div class="item-value"  style="flex:2">
          <a-input v-model:value="props.infoData.address" :disabled="!props.control"/>
        </div>
      </div>
    </div>
    <div class="row">
      <div class="item">
        <div class="label">图斑面积：</div>
        <div class="item-value">
          <a-input v-model:value="props.infoData.area" :disabled="!props.control"/>
        </div>
      </div>
      <div class="item">
        <div class="label">耕地面积：</div>
        <div class="item-value">
          <a-input v-model:value="props.infoData.gengdi_area" :disabled="!props.control"/>
        </div>
      </div>
      <div class="item">
        <div class="label">占重点区域面积：</div>
        <div class="item-value">
          <a-input v-model:value="props.infoData.zhongdianquyu_area" :disabled="!props.control"/>
        </div>
      </div>
      <div class="item" v-if="props.type == '违法用地'">
        <div class="label">图斑来源：</div>
        <div class="item-value">
          <a-select 
            style="width: 100%"
            v-model:value="props.infoData.tubanlaiyuan"
            :options="tubanlaiyuanOptions"
            placeholder="请选择图斑来源"
            :disabled="!props.control"/>
        </div>
      </div>
      <div class="item" v-else></div>
    </div>
    <div class="row">
      <div class="item">
        <div class="label">占空间规划面积：</div>
        <div class="item-value">
          <a-input v-model:value="props.infoData.guotukongjianguihua_area" :disabled="!props.control"/>
        </div>
      </div>
      <div class="item">
        <div class="label">占农用地面积：</div>
        <div class="item-value">
          <a-input v-model:value="props.infoData.nongyongdi_area" :disabled="!props.control"/>
        </div>
      </div>
      <div class="item">
        <div class="label">占永久基本农田面积：</div>
        <div class="item-value">
          <a-input v-model:value="props.infoData.yongjiujibennongtian_area" :disabled="!props.control"/>
        </div>
      </div>
      <div class="item">
        <div class="label">占生态红线面积：</div>
        <div class="item-value">
          <a-input v-model:value="props.infoData.shengtaibaohuhongxian_area" :disabled="!props.control"/>
        </div>
      </div>
      <!-- <div class="item">
        <div class="label" v-if="false">是否县级访问：</div>
        <div class="item-value" v-if="false">
          <a-select
            style="width: 100%"
            v-model:value="props.infoData.countyusable"
            :options="yesOrNoOptions"
            :defaultValue="1"
            :disabled="!props.control"/>
        </div>
      </div> -->
    </div>
    <div class="row">
      <div class="item">
        <div class="label">前影像名称：</div>
        <div class="item-value" style="flex:2">
          <a-input v-model:value="props.infoData.pre_phase_img" disabled />
        </div>
      </div>
      <div class="item">
        <div class="label">前时相时间：</div>
        <div class="item-value" style="flex:2">
          <a-input v-model:value="props.infoData.pre_phase_time" disabled/>
        </div>
      </div>
      <div class="item">
        <div class="label">备注：</div>
        <div class="item-value" style="flex:2">
          <a-input v-model:value="props.infoData.remark" :disabled="!props.control"/>
        </div>
      </div>
    </div>
    <div class="row">
      <div class="item">
        <div class="label">后影像名称：</div>
        <div class="item-value" style="flex:2">
          <a-input v-model:value="props.infoData.later_phase_img" disabled/>
        </div>
      </div>
      <div class="item">
        <div class="label">后时相时间：</div>
        <div class="item-value" style="flex:2">
          <a-input v-model:value="props.infoData.later_phase_time" disabled/>
        </div>
      </div>
      <div class="item">
        <div class="label">经纬度：</div>
        <div class="item-value" style="flex:2;display: flex">
          <a-input id="lnglat" style="margin-right: 15px;" :value="`${props.infoData.lng},${props.infoData.lat}`" disabled/>
          <a-button @click="copyText">复制</a-button>
          <textarea id="copyText" style="position: absolute;left: -9999px;top: -9999px;" :value="`${props.infoData.lng},${props.infoData.lat}`"/>
        </div>
      </div>
    </div>
    <div class="row">
      <div class="item">
        <div class="label">判读人：</div>
        <div class="item-value" style="flex:2">
          <a-input v-model:value="props.infoData.identification_user" disabled/>
        </div>
      </div>
      <div class="item">
        <div class="label">判读时间：</div>
        <div class="item-value" style="flex:2">
          <a-input v-model:value="props.infoData.identification_time" disabled/>
        </div>
      </div>
      <div class="item">
        <div class="label">情况说明：</div>
        <div class="item-value" style="flex:2">
          <a-input v-model:value="props.infoData.resubmitremark" disabled/>
        </div>
      </div>
    </div>
    <div class="row">
      <div class="item" style="width: 100%;">
        <div class="label">图片：</div>
        <div style="flex:9;display:flex;">
          <a-image-preview-group>
            <div class="video-item" v-for="(item, index) in fileList" :key="index" style="display: inline-block;position:relative;">
              <div v-if="props.control" class="video-delete-btn" @click="handlerDelete(index)">
                <CloseOutlined />
              </div>
              <a-image :src="item.url" style="width:100px;height:100px;" />
            </div>
          </a-image-preview-group>
          <Upload
            v-if="props.control"
            list-type="picture-card"
            :showUploadList="false"
            :custom-request="customRequest"
            @change="handleChange"
            :disabled="!props.control"
          >
            <div>
              <plus-outlined />
              <div style="margin-top: 8px">Upload</div>
            </div>
          </Upload>
        </div>
      </div>
    </div>
    <div style="width: 50%; height: 300px; margin-bottom: 10px;">
      <MapboxMap 
        @mapOnLoad="onMapboxLoad"
        ref="MapboxComponent"/>
    </div>
    <div class="footer">
      <div class="button-div">
        <a-button style="margin-right: 10px;" @click="emits('closeModal')">关闭弹窗</a-button>
        <a-button v-if="props.control" style="margin-right: 10px;" type="primary" class="danger-button" @click="emits('closeCase',props.infoData.id)">关闭线索</a-button>
        <a-button v-if="props.control" style="margin-right: 10px;" type="primary" @click="submit">审核通过</a-button>
        <a-button v-if="props.control && props.infoData.original_case_no" style="margin-right: 10px;" type="primary" class="danger-button" @click="reSubmit">复提</a-button>
      </div>
    </div>
  </div>
</a-spin>
</template>

<script setup lang="ts">
import { defineProps, ref, watch, onMounted, defineEmits, createVNode } from "vue"
import { PlusOutlined, CloseOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { Upload, message, Modal } from 'ant-design-vue';
import { uploadFile } from '@/api/formrender/index';
import { getAppEnvConfig } from '@/utils/env';
import { getLoad } from '@/api/sys/sysDataItemDetail';
import { getChildrenTree } from '@/api/demo/system';
import MapboxMap from '@/components/MapboxMaps/MapComponent.vue';
import { getGeom } from '@/api/sys/layerManagement';
import { typenameKey } from '@/views/demo/audit/util'
import axios from "axios";
import { tubanbiaoqian1Options, tubanbiaoqian2Options } from './util'
import { IsReSubmit } from '@/api/audit/index'
import { SubjectKeyObj } from '@/views/demo/audit/util';

const props = defineProps(['infoData','control','type','modalLoading'])
const emits = defineEmits(['handleOk','closeModal','closeCase','reSubmit','changeLoading'])

const typenameOptions = ref([])
const tubanlaiyuanOptions = ref([])
const countyOptions = ref([])
const streetOptions = ref([])
const communityOptions = ref([])
const fileList = ref<any>([])
const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');
const geomsList = ref()
const MapboxComponent = ref();
const yesOrNoOptions = ref([
  { label: '是', value: 1 },
  { label: '否', value: 0 },
])
const caseDescription = ref(["",""])

onMounted(() => {
  if(props.type == '违法用地'){
    if(props.infoData.case_description){
      caseDescription.value = props.infoData.case_description.split('-')
      console.log('caseDescription1.value',caseDescription.value)
    }
  }
  getLoad({code: typenameKey[props.type]}).then(res => {
    typenameOptions.value = res.map(item => {
      return {
        label: item.itemName,
        value: item.itemValue
      }
    })
  })
  getLoad({code: 'wfydtbly'}).then(res => {
    tubanlaiyuanOptions.value = res.map(item => {
      return {
        label: item.itemName,
        value: item.itemValue
      }
    })
  })
  getChildrenTree({ parentId: 371300 }).then(res => {
    countyOptions.value = res.map(item => {
      return {
        label: item.name,
        value: item.id.toString(),
      }
    })
  })
  props.infoData.countyid && getChildrenTree({ parentId: props.infoData.countyid }).then(res => {
    streetOptions.value = res.map(item => {
      return {
        label: item.name,
        value: item.id.toString(),
      }
    })
  })
  props.infoData.streetid && getChildrenTree({ parentId: props.infoData.streetid }).then(res => {
    communityOptions.value = res.map(item => {
      return {
        label: item.name,
        value: item.id.toString(),
      }
    })
  })
  const { VITE_GLOB_INFO_IMAGE_URL } = getAppEnvConfig();
  props.infoData.casepic && props.infoData.casepic.split(',').forEach(item => {
      fileList.value.push({
        uid: '-1',
        name: item,
        status: 'done',
        url: VITE_GLOB_INFO_IMAGE_URL + '/' + item,
      })
    })
})
watch(() => fileList.value.length, (val) => {
  props.infoData.casepic = fileList.value.map(item => item.name).join(',')
})

const handleChange = (info) => {
  if (info.file.status !== 'uploading') {
  }
  if (info.file.status === 'done') {
  } else if (info.file.status === 'error') {
  }
};
const customRequest = (file) => {
  console.log('handleCustomRequest',file)
  const { VITE_GLOB_INFO_IMAGE_URL } = getAppEnvConfig();
  const formData = new FormData()
  formData.append('files', file.file)
  axios({
    method: 'post',
    url: `${VITE_GLOB_INFO_IMAGE_URL}/api/Platform/Upload`,
    params: { project: 'DroneEnforcement'},
    data: formData,
    headers: {
      'Content-type': 'multipart/form-data',
    },
  }).then(res => {
    let data = res.data.result
    console.log(res)
    fileList.value?.push({
      uid: '-1',
      name: data[0].filePath,
      status: 'done',
      url: VITE_GLOB_INFO_IMAGE_URL + '/' + data[0].filePath,
    });
  })
}
const handlePreview = () => {

}
const handleRemove = () => {

}
const handlerDelete = (index) => {
  fileList.value.splice(index, 1);
}
const handlerPreviewImage = (url,list) => {
  
}
const submitApi = () => {
  Modal.confirm({
    title: '确认审核通过吗？',
    icon: createVNode(ExclamationCircleOutlined),
    okText: '确认',
    cancelText: '取消',
    onOk: () => {
      IsReSubmit({originalcaseno: props.infoData.original_case_no, subjectkey: SubjectKeyObj[props.type]}).then(res => {
        if(res){
          if(props.type == '违法用地'){
            props.infoData.case_description = caseDescription.value.join('-')
          }
          let params = {
            ...props.infoData,
            subject: props.type,
          }
          emits('handleOk',params)
        }else{
          message.error('审核失败')
        }
      })
    }
  })
  
}
const submit = () => {
  if(props.type != '违法用地'){
    submitApi()
    return
  }
  switch(props.infoData.typename){
    case '农用地':
      if(Number(props.infoData.nongyongdi_area) > 0){
        submitApi()
        return
      }
      Modal.confirm({
        title: '农用地 类型时 占农用地面积 需大于0',
        icon: createVNode(ExclamationCircleOutlined),
        okText: '继续',
        onOk() {
          submitApi()
        }
      });
    break
    case '建设用地':
      if(Number(props.infoData.nongyongdi_area) == 0){
        submitApi()
        return
      }
      Modal.confirm({
        title: '建设用地 类型时 占农用地面积 需为0',
        icon: createVNode(ExclamationCircleOutlined),
        okText: '继续',
        onOk() {
          submitApi()
        }
      })
    break
    default:
      submitApi()
  }
}
const reSubmit = () => {
  emits('reSubmit',props.infoData.original_case_no)
}
const copyText = () => {
  const copyTextDom = document.getElementById('copyText')
  console.log(copyTextDom)
  if(copyTextDom){
    copyTextDom.select()
    document.execCommand('Copy');
    message.success('复制成功')
  }
}
async function changeTask() {
  let getGeomPrams = {
    TableName: 'drone_shp_data ',
    FieldName: 'gid',
    FieldValue: props.infoData.geomid?.split(','),
    page: 1,
    limit: 999,
    key: null,
  };
  if (props.infoData.geomid) {
    getGeom(getGeomPrams).then((res) => {
      let geoms: Array<{ key: string; mapgeom: any }> = [];
      if (res) {
        if (res.items?.length > 0) {
          res.items.forEach((item, index) => {
            let geom = {
              key: item.gid,
              mapgeom: item.geometry,
            };
            geoms.push(geom);
            geomsList.value = geoms;
          });
        }
        MapboxComponent.value.handlerDraw('Details', geoms, false);
      } else {
        geomsList.value = null;
        message.error('当前数据没有图斑！');
      }
    });
  } else {
    message.error('当前数据没有图斑！');
  }
}
const onMapboxLoad = () => {
  changeTask();
}
const handleCountyChange = (value,item) => {
  props.infoData.countyname = item.label
  props.infoData.streetid = ''
  props.infoData.streetname = ''
  props.infoData.communityid = ''
  props.infoData.communityname = ''
  getChildrenTree({ parentId: value }).then(res => {
    streetOptions.value = res.map(item => {
      return {
        label: item.name,
        value: item.id.toString(),
      }
    })
    communityOptions.value = []
  })
}
const handleStreetChange = (value,item) => {
  props.infoData.streetname = item.label
  props.infoData.communityid = ''
  props.infoData.communityname = ''
  getChildrenTree({ parentId: value }).then(res => {
    communityOptions.value = res.map(item => {
      return {
        label: item.name,
        value: item.id.toString(),
      }
    })
  })
}
const handleCommunityChange = (value,item) => {
  props.infoData.communityname = item.label
}
</script>

<style lang="scss" scoped>
:deep(.ant-image){
  margin-right: 10px;
  margin-bottom: 10px;
}
.video-delete-btn {
  position: absolute;
  top: 0px;
  right: 10px;
  width: 30px;
  height: 30px;
  border-bottom-left-radius: 80%;
  background: rgb(0 0 0 / 20%);
  color: #fff;
  line-height: 30px;
  text-align: center;
  z-index: 999;
}
.modal-content{
  padding: 20px;
}
.row{
  display: flex;
  margin-bottom: 15px;
}
.select-width{
  width:100%;
}
.item{
  display: flex;
  flex:1;
  .label{
    flex: 1;
    padding: 0px 15px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .item-value{
    padding: 0px 15px;
    flex:1;
  }
}
.button-div{
  display: flex;
  justify-content: flex-end;
  .danger-button{
    background: #ed6f6f;
    &:hover{
      background: #faa19d;
    }
  }
}
</style>
