<template>
  <CusDialog
    :show="show"
    :title="titleCpt"
    @onClose="$emit('update:show', false)"
    width="800px"
    max-height="80%"
    @onSubmit="onSubmit"
    :loading="state.loading"
  >
    <div class="__cus-dialog-form">
      <CusForm ref="ref_form" label-width="100px">
        <div class="__cus-title_1">场景设定</div>
        <el-col :span="12">
          <CusFormColumn
            :span="24"
            required
            label="预警名称"
            v-model:param="state.form.name"
          />
          <CusFormColumn
            :span="24"
            required
            label="预警级别"
            v-model:param="state.form.level"
            link="select"
            :options="DictionaryStore.warningLevelList"
          />
          <CusFormColumn
            :span="24"
            required
            label="预警模型"
            v-model:param="state.modelDetail.name"
            :disabled="true"
          />
        </el-col>
        <el-col :span="12">
          <CusFormColumn
            :span="24"
            label="场景描述"
            v-model:param="state.form.description"
            type="textarea"
            :rows="6"
          />
        </el-col>
        <div class="__cus-title_1">参数配置</div>
        <div class="params-table" style="width: 100%">
          <CusTable
            :data="state.paramList"
            :table-head="[
              {value: 'name', label: '参数'},
              {value: 'value', label: '值'},
              {value: 'unit', label: '单位'},
            ]"
            :no-page="true"
          >
            <template #value-column-value="{scope}">
              <CusFormColumn
                :required="scope.row.required"
                class="__cus-table-form-column"
                :span="24"
                v-model:param="scope.row.value"
                :default-error-msg="'请输入' + scope.row.name"
                link="number"
                :placeholder="'推荐值：' + scope.row.recommendValue"
              />
            </template>
          </CusTable>
        </div>
        <div class="__cus-title_1" v-if="state.modelDetail.areaConfig != 0 || state.modelDetail.allowAreaConfig != 0">区域配置</div>
        <el-col :span="24" v-if="state.modelDetail.areaConfig != 0">
          <el-row>
            <CusFormColumn
              label-width="140px"
              :required="state.modelDetail.areaConfig == 2"
              :span="20"
              label="预警区域选择"
              v-model:param="state.areaIds.warning"
              link="select"
              multiple
              :options="DictionaryStore.warningAreaList.filter(v => !state.areaIds.white.includes(v.id))"
              label-key="name"
              value-key="id"
            />
            <el-col :span="4" v-if="state.areaIds.warning.length > 0">
              <div class="view-area __hover" @click="onAreaMap(state.areaIds.warning)">查看区域</div>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="24" v-if="state.modelDetail.allowAreaConfig != 0">
          <el-row>
            <CusFormColumn
              label-width="140px"
              :required="state.modelDetail.allowAreaConfig == 2"
              :span="20"
              label="白名单区域选择"
              v-model:param="state.areaIds.white"
              link="select"
              multiple
              :options="DictionaryStore.warningAreaList.filter(v => !state.areaIds.warning.includes(v.id))"
              label-key="name"
              value-key="id"
            />
            <el-col :span="4" v-if="state.areaIds.white.length > 0">
              <div class="view-area __hover" @click="onAreaMap(state.areaIds.white)">查看区域</div>
            </el-col>
          </el-row>
        </el-col>
      </CusForm>
      <areaMap v-model:show="state.areaMap.show" :transfer="state.areaMap.transfer"/>
    </div>
  </CusDialog>
</template>

<script setup lang="ts">
import {computed, getCurrentInstance, nextTick, onMounted, reactive, ref, watch} from "vue";
import {useDictionaryStore} from "@/stores";
import {ElMessage, ElMessageBox} from "element-plus";
import areaMap from './area-map.vue'
import {warnModelDetail} from "@/api/modules/web/model";
import {warnAreaQueryAll} from "@/api/modules/web/area";
import {warnRuleAdd, warnRuleDetail, warnRuleEdit} from "@/api/modules/web/rule";

const emit = defineEmits(['update:show', 'refresh'])
const {proxy} = getCurrentInstance()
const DictionaryStore = useDictionaryStore()
const props = defineProps({
  show: {default: false},
  transfer: {}
 })
const state: any = reactive({
  form: {},
  loading: false,
  areaIds: {
    warning: [],
    white: [],
  },
  areaMap: {
    show: false,
    transfer: {}
  },
  modelDetail: {},
  paramList: [],
})
const ref_form = ref()
const titleCpt = computed(() => {
  let t = '查看预警规则'
  switch (props.transfer.mode) {
    case 'add': t = '新增预警规则'
      break
    case 'edit': t = '编辑预警规则'
      break
  }
  return t
})
const onSubmit = () => {
  ref_form.value.submit().then(() => {
    ElMessageBox.confirm("是否提交?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    } as any).then(() => {
      state.loading = true
      const params = {
        enabled: false,
        ...state.form,
        modelId: props.transfer.modelId,
        paramList: state.paramList.map(v => ({id: v.id, value: v.value})),
        areaTypeList: []
      }
      if (state.modelDetail.areaConfig != 0) {
        state.areaIds.warning.forEach(v => {
          params.areaTypeList.push({id: v, type: 1})
        })
      }
      if (state.modelDetail.allowAreaConfig != 0) {
        state.areaIds.white.forEach(v => {
          params.areaTypeList.push({id: v, type: 2})
        })
      }
      if (props.transfer.mode == 'add') {
        warnRuleAdd(params).then(res => {
          if (res.code == 0) {
            ElMessage.success('新增成功！')
            emit('update:show', false)
            emit('refresh')
            state.loading = false
          } else {
            ElMessage.error(res.msg)
          }
        }).catch(() => {
          state.loading = false
        })
      } else {
        warnRuleEdit(params).then(res => {
          if (res.code == 0) {
            ElMessage.success('编辑成功！')
            emit('update:show', false)
            emit('refresh')
            state.loading = false
          } else {
            ElMessage.error(res.msg)
          }
        }).catch(() => {
          state.loading = false
        })
      }
    }).catch(() => {})
  }).catch((e) => {
    ElMessage({
      message: e[0].message,
      grouping: true,
      type: 'warning',
    })
  })
}
const initDetail = () => {
  warnRuleDetail(proxy.$util.formatGetParam({id: props.transfer.id})).then(res => {
    if (res.code == 0) {
      state.form = res.data
      state.form.areaTypeList.forEach(v => {
        if (v.type == 1) {
          state.areaIds.warning.push(v.id)
        } else {
          state.areaIds.white.push(v.id)
        }
      })
      initModel(state.form.modelId)
    } else {
      ElMessage.error(res.msg)
    }
  })
}
const initArea = () => {
  warnAreaQueryAll().then(res => {
    DictionaryStore.initOtherDict('warningArea', res.data.map(v => {
      v.dictLabel = v.name
      v.dictValue = v.id
      return v
    }))
  })
}
watch(() => props.show, (n) => {
  if (n) {
    state.loading = true
    initDictionary()
    state.form = {}
    state.modelDetail = {}
    state.paramList = []
    state.areaIds.white = []
    state.areaIds.warning = []
    if (props.transfer.mode !== 'add') {
      initDetail()
    } else {
      initModel(props.transfer.modelId)
    }
    nextTick(() => {
      ref_form.value.reset()
    })
  }
})
const initModel = (id) => {
  warnModelDetail(proxy.$util.formatGetParam({id: id})).then(res => {
    if (res.code == 0) {
      state.modelDetail = res.data
      state.paramList = state.modelDetail.paramDictList
      if (props.transfer.mode != 'add') {
        state.paramList.forEach(v => {
          state.form.paramList.forEach(v2 => {
            if (v.id == v2.id) {
              v.value = v2.value
            }
          })
        })
      }
      state.loading = false
    } else {
      ElMessage.error(res.msg)
    }
  })
}
const onAreaMap = (areas) => {
  state.areaMap.transfer = {
    areas: areas
  }
  state.areaMap.show = true
}
onMounted(() => {
  initArea()
})
const initDictionary = () => {
  // DictionaryStore.initDict('format_type')
}
</script>

<style lang="scss" scoped>
.__cus-title_1 {
  margin-bottom: 20px;
}
.params-table {
  margin-bottom: 20px;
}
.view-area {
  line-height: 40px;
  margin-left: 20px;
  font-weight: 400;
  font-size: 16px;
  color: #81AFFF;
}
</style>
