<template>
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row>
        <a-col :span="20" style="margin-bottom: 10px;">
          <a-button @click="templateVisible = true">导入模板</a-button>
          <a-modal title="导入模板" :visible="templateVisible" @ok="chooseTemplate" @cancel="templateVisible = false">
            <a-radio-group v-model:value="templateId">
              <template v-for="item in templateData">
                <div>
                  <a-radio :value="item.id">
                    {{ item.emerName }}
                  </a-radio>
                </div>
              </template>
            </a-radio-group>
          </a-modal>
        </a-col>

        <a-col :span="12">
          <a-form-item label="预案编号" v-bind="validateInfos.emerNum">
            <a-input v-model:value="formData.emerNum" placeholder="请输入预案编号" disabled></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="预案名称" v-bind="validateInfos.emerName">
            <a-input v-model:value="formData.emerName" placeholder="请输入预案名称" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="预案类型" v-bind="validateInfos.emerType">
            <j-dict-select-tag v-model:value="formData.emerType" dictCode="ms_emer_type" :string-to-number="true"
              placeholder="请选择预案类型" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="风险等级" v-bind="validateInfos.emerLevel">
            <j-dict-select-tag v-model:value="formData.emerLevel" dictCode="ms_emer_level" :string-to-number="true"
              placeholder="请选择预案风险等级" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <!-- <a-col :span="12">
          <a-form-item label="预案状态" v-bind="validateInfos.emerStatus">
	          <j-dict-select-tag v-model:value="formData.emerStatus" dictCode="ms_emer_status" placeholder="请选择预案状态" :disabled="disabled"/>
          </a-form-item>
        </a-col> -->
        <a-col :span="12">
          <a-form-item label="编制人" v-bind="validateInfos.emerPreparedBy">
            <a-input v-model:value="formData.emerPreparedBy" placeholder="请输入编制人" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item :labelCol="{ xs: { span: 24 }, sm: { span: 5 }, md: { span: 3 }, }" label="预案描述"
            v-bind="validateInfos.emerDescription">
            <a-input v-model:value="formData.emerDescription" placeholder="请输入预案描述" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="预案步骤内容" v-bind="validateInfos.emerStepContent">
          </a-form-item>
        </a-col>
        <!-- <a-col :span="12">
          <a-form-item label="审批意见" v-bind="validateInfos.emerApprovalOpinion">
	          <a-textarea v-model:value="formData.emerApprovalOpinion" rows="4" placeholder="请输入审批意见" :disabled="disabled"/>
          </a-form-item>
        </a-col> -->
        <!-- <a-col :span="12">
          <a-form-item label="是否为模板" v-bind="validateInfos.emerIsTemplate">
	          <j-dict-select-tag v-model:value="formData.emerIsTemplate" dictCode="" placeholder="请选择是否为模板" :disabled="disabled"/>
          </a-form-item>
        </a-col> -->
        <a-col :span="24">
          <a-space direction="vertical" :size="24" style="width: 100%">
            <a-steps v-model:current="stepCurrent" @change="keepFocus">
              <a-step v-for="(_item, index) in stepList" :key="index" :title="`第 ${index + 1} 步`" />
            </a-steps>
            <a-textarea :disabled="formDisabled" ref="stepText" v-model:value="stepList[stepCurrent]"
              style="height: 30vh;" />
          </a-space>
          <a-space style="margin-top: 10px;" v-if="stepShow">
            <a-button type="primary" :disabled="stepList.length >= 5 || disabled" @click="addStep">添加步骤</a-button>
            <a-button type="danger" :disabled="stepList.length == 1 || disabled" @click="removeStep">删除此步骤</a-button>
          </a-space>
        </a-col>

      </a-row>
    </a-form>
  </a-spin>
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick, computed, onMounted } from 'vue';
import { defHttp } from '/@/utils/http/axios';
import { useMessage } from '/@/hooks/web/useMessage';
import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
import { getValueType } from '/@/utils';
import { saveOrUpdate } from '../MsEmergencyPlan.api';
import { Form } from 'ant-design-vue';
import _ from 'lodash'

const props = defineProps({
  formDisabled: { type: Boolean, default: false },
  formData: { type: Object, default: () => { } },
  formBpm: { type: Boolean, default: true }
});
const formRef = ref();
const useForm = Form.useForm;
const emit = defineEmits(['register', 'ok']);
const formData = reactive<Record<string, any>>({
  id: '',
  emerNum: '',
  emerName: '',
  emerDescription: '',
  emerType: undefined,
  emerLevel: undefined,
  emerStatus: undefined,
  emerPreparedBy: '',
  emerStepContent: '',
  emerApprovalOpinion: '',
  emerIsTemplate: undefined,
});
const { createMessage } = useMessage();
const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 6 } });
const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
const confirmLoading = ref<boolean>(false);
//表单验证
const validatorRules = {
  emerType: [{ required: true, message: '请输入预案类型!' },],
  emerName: [{ required: true, message: '请输入预案名称!' },],
  emerPreparedBy: [{ required: true, message: '请输入编制人!' },],
  emerLevel: [{ required: true, message: '请选择预案风险等级!' },],
  emerDescription: [{ required: true, message: '请输入预案描述!' },],
};
const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: true });


//导入模板
const templateVisible = ref(false);
const templateData: any = ref([]);
const templateId: any = ref(1);
const stepCurrent: any = ref(0);
const stepShow: any = ref(false);
const stepList: any = ref(["", "", ""]);
const stepText: any = ref();

// 保持焦点 用于步骤输入框
function keepFocus() {
  stepText.value.focus();
}
// 添加步骤
function addStep() {
  if (stepList.value.length < 5) {
    stepList.value.push("");
    stepText.value.focus();
  } else {
    createMessage.error("最多只能添加5个步骤")
  }
}
// 删除步骤
function removeStep() {
  if (stepList.value.length > 1) {
    stepList.value.splice(stepCurrent.value, 1);
    stepCurrent.value = stepCurrent.value == 0 ? 0 : stepCurrent.value - 1;
    stepText.value.focus();
  } else {
    createMessage.error("至少要有一个步骤")
  }
}
//选择模板
function chooseTemplate() {
  templateData.value.forEach(element => {
    if (element.id == templateId.value) {
      let obj = {
        emerType: element.emerType,
        emerType_dictText: element.emerType_dictText,
        emerLevel: element.emerLevel,
        emerLevel_dictText: element.emerLevel_dictText,
        emerPreparedBy: element.emerPreparedBy,
        emerStepContent: element.emerStepContent,
        emerDescription: element.emerDescription
      }
      // this.model = Object.assign(this.model, obj);
      //赋值
      Object.assign(formData, obj);
      // 设置步骤内容
      // if (this.model.emerStepContent) {
      //   this.stepList = JSON.parse(this.model.emerStepContent);
      // }
      if (formData.emerStepContent) {
        stepList.value = JSON.parse(formData.emerStepContent);
      }
      templateVisible.value = false
    }
  });
}




// 表单禁用
const disabled = computed(() => {
  if (props.formBpm === true) {
    if (props.formData.disabled === false) {
      return false;
    } else {
      return true;
    }
  }
  return props.formDisabled;
});

onMounted(() => {
  defHttp.get({
    url: "/military/msEmergencyPlan/list",
    params: { emerIsTemplate: 1 }
  }, { isTransformResponse: false })
    // getAction(this.url.list, { emerIsTemplate: 1 })
    .then(res => {
      if (res.success) {
        templateData.value = res.result.records
      }
    })
})
/*
* 生成一个由日期，时间和4位随机数组成的代码
*/
function dateAndRandomNum() {
  var day2 = new Date();
  // 获取年份
  var s2 = day2.getFullYear() + "";
  // 获取两位数月份
  if ((day2.getMonth() + 1) < 10) {
    s2 = s2 + "0" + (day2.getMonth() + 1) + "";
  } else {
    s2 = s2 + (day2.getMonth() + 1) + "";
  }
  // 获取两位数日期
  if (day2.getDate() < 10) {
    s2 = s2 + "0" + day2.getDate() + "";
  } else {
    s2 = s2 + day2.getDate() + "";
  }
  // 获取两位数小时
  if (day2.getHours() < 10) {
    s2 = s2 + "0" + day2.getHours() + "";
  } else {
    s2 = s2 + day2.getHours() + "";
  }
  // 获取两位数分钟
  if (day2.getMinutes() < 10) {
    s2 = s2 + "0" + day2.getMinutes() + "";
  } else {
    s2 = s2 + day2.getMinutes() + "";
  }
  // 获取两位数秒
  if (day2.getSeconds() < 10) {
    s2 = s2 + "0" + day2.getSeconds() + "";
  } else {
    s2 = s2 + day2.getSeconds() + "";
  }
  // 生成4位随机数
  for (let i = 0; i < 4; i++) {
    s2 = s2 + Math.floor(Math.random() * 10);
  }
  return s2;
}
/**
 * 新增
 */
function add() {
  edit({
    emerStatus: 0,
    emerNum: dateAndRandomNum()
  });
}

/**
 * 编辑
 */
function edit(record) {
  // console.log(record);

  nextTick(() => {
    resetFields();
    //赋值
    Object.assign(formData, record);
    stepShow.value = true;
    // 设置步骤内容
    if (formData.emerStepContent) {
      stepList.value = JSON.parse(formData.emerStepContent);
    }
  });
}

/**
 * 提交数据
 */
async function submitForm() {
  // 触发表单验证
  await validate();
  confirmLoading.value = true;
  const isUpdate = ref<boolean>(false);
  //时间格式化
  let model = formData;
  if (model.id) {
    isUpdate.value = true;
  }
  console.log(stepList.value);
  //循环数据
  for (let data in model) {
    //如果该数据是数组并且是字符串类型
    if (model[data] instanceof Array) {
      let valueType = getValueType(formRef.value.getProps, data);
      //如果是字符串类型的需要变成以逗号分割的字符串
      if (valueType === 'string') {
        model[data] = model[data].join(',');
      }
    }
  }

  // 设置步骤内容
  model.emerStepContent = JSON.stringify(stepList.value);
  // 状态为不通过时
  if (model.emerStatus == 3) {
    // 删除审批意见
    model.emerApprovalOpinion = ""
    model.emerStatus = 0;
  }


  await saveOrUpdate(model, isUpdate.value)
    .then((res) => {
      if (res.success) {
        createMessage.success(res.message);
        emit('ok');
      } else {
        createMessage.warning(res.message);
      }
    })
    .finally(() => {
      confirmLoading.value = false;
    });
}


defineExpose({
  add,
  edit,
  submitForm,
});
</script>

<style lang="less" scoped>
.antd-modal-form {
  min-height: 500px !important;
  overflow-y: auto;
  padding: 24px 24px 24px 24px;
}
</style>
