<template>
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row>
        <a-col :span="12">
          <a-form-item label="线路名称" v-bind="validateInfos.name">
            <a-input v-model:value="formData.name" placeholder="请输入线路名称" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="首尾相连" v-bind="validateInfos.isLoop">
            <!-- <j-dict-select-tag type='radio' v-model:value="formData.isLoop" dictCode="is_consumable" placeholder="请选择首尾相连"
              :disabled="disabled" /> -->
            <!-- <j-dict-select-tag v-model:value="formData.isLoop" dictCode="is_consumable" :string-to-number="true"
              placeholder="请选择..." :disabled="disabled" /> -->
            <j-switch v-model:value="formData.isLoop" :options="[true, false]" :disabled="disabled"></j-switch>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="深度检测" v-bind="validateInfos.isDepthCheck">
            <!-- <j-dict-select-tag type='radio' v-model:value="formData.isDepthCheck" dictCode="is_consumable"
              placeholder="请选择深度检测" :disabled="disabled" /> -->
            <!-- <j-dict-select-tag v-model:value="formData.isDepthCheck" dictCode="is_consumable" :string-to-number="true"
              placeholder="请选择..." :disabled="disabled" /> -->
            <j-switch v-model:value="formData.isDepthCheck" :options="[true, false]" :disabled="disabled"></j-switch>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="宽度" v-bind="validateInfos.width">
            <a-input-number v-model:value="formData.width" placeholder="请输入宽度" style="width: 100%" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="插值方式" v-bind="validateInfos.interpolation">
            <j-dict-select-tag v-model:value="formData.interpolation" dictCode="dt_arc_type" placeholder="请选择插值方式"
              :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="材质类型" v-bind="validateInfos.materialType">
            <j-dict-select-tag v-model:value="formData.materialType" dictCode="map_line_material_type"
              placeholder="请选择材质类型" :string-to-number="true" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="颜色" v-bind="validateInfos.color">
            <ColorPicker v-model:pureColor="pureColor" v-model:gradientColor="gradientColor"
              v-on:pureColorChange="pureColorChange" v-on:update:pureColor="() => { }" v-on:activeKeyChange="() => { }"
              v-on:update:activeKey="() => { }" v-on:gradientColorChange="() => { }" v-on:update:gradientColor="() => { }"
              style="width: 80%;" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="间隔颜色" v-bind="validateInfos.intervalColor">
            <!-- <a-input v-model:value="formData.intervalColor" placeholder="请输入间隔颜色" :disabled="disabled"></a-input> -->
            <ColorPicker v-model:pureColor="intervalColor" v-model:gradientColor="gradientColorIntervalColor"
              v-on:pureColorChange="pureColorChangeIntervalColor" style="width: 80%;" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="虚线长度" v-bind="validateInfos.dashLength">
            <a-input-number v-model:value="formData.dashLength" placeholder="请输入虚线长度" style="width: 100%"
              :disabled="disabled" />
          </a-form-item>
        </a-col>
        <!-- <a-col :span="12">
          <a-form-item label="虚线样式" v-bind="validateInfos.dashStyle">
            <a-input-number v-model:value="formData.dashStyle" placeholder="请输入虚线样式" style="width: 100%"
              :disabled="disabled" />
          </a-form-item>
        </a-col> -->
        <a-col :span="12">
          <a-form-item label="循环周期（帧）" v-bind="validateInfos.cycleFrame">
            <a-input-number v-model:value="formData.cycleFrame" placeholder="请输入循环周期（帧）" style="width: 100%"
              :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="位置" v-bind="validateInfos.positions">
            <a-textarea v-model:value="formData.positions" :rows="4" placeholder="请输入位置" :disabled="disabled" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-spin>
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick, computed, onMounted, watch } from 'vue';
import { defHttp } from '/@/utils/http/axios';
import { useMessage } from '/@/hooks/web/useMessage';
import JSwitch from '/@/components/Form/src/jeecg/components/JSwitch.vue';
import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
import { getValueType } from '/@/utils';
import { saveOrUpdate } from '../MsMapLine.api';
import { Form } from 'ant-design-vue';
import { ColorPicker } from "vue3-colorpicker";
import "vue3-colorpicker/style.css";


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: '',
  name: '',
  isLoop: undefined,
  isDepthCheck: undefined,
  width: undefined,
  interpolation: '',
  materialType: undefined,
  color: '',
  intervalColor: '',
  dashLength: undefined,
  dashStyle: undefined,
  cycleFrame: undefined,
  positions: '',
});
const { createMessage } = useMessage();
const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
const confirmLoading = ref<boolean>(false);
//表单验证
const validatorRules = {
  name: [{ required: true, message: '请输入线路名称!' },],
  materialType: [{ required: true, message: '请选择模型材质类型!' },],
  interpolation: [{ required: true, message: '请选择插值方式!' },],
  color: [{ required: true, message: '请输入颜色!' },],
  intervalColor: [{ required: true, message: '请输入间隔颜色!' },],
  cycleFrame: [{ required: true, message: '请输入循环周期!' },],
  isLoop: [{ required: true, message: '请选择是否首尾相连!' },],
  isDepthCheck: [{ required: true, message: '请选择是否深度检测!' },],
  width: [{ required: true, message: '请输入宽度!' },],
  dashLength: [{ required: true, message: '请输入虚线长度!' },],
};
const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: true });

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

// 调色器颜色和透明度字符串
const pureColor = ref<any>({ "r": 255, "g": 255, "b": 0, "a": 0.5 });
const gradientColor = ref<string>("");
const intervalColor = ref<any>({ "r": 255, "g": 255, "b": 0, "a": 0.5 });
const gradientColorIntervalColor = ref<string>("");

function pureColorChange(color: any) {
  // console.log("color", color);
  //去除所有空格
  color = color.replace(/\s*/g, "");
  formData.color = "[" + rgba2arr(color) + "]"
}

function pureColorChangeIntervalColor(color: any) {
  //去除所有空格
  color = color.replace(/\s*/g, "");
  formData.intervalColor = "[" + rgba2arr(color) + "]"
}

/**
 * 字符串rgba转数组
 * @param {string} color "rgba(1,2,3,4)"
 * @param {boolean} normalized 是否被255归一化
 * @return {array} [1,2,3,4]
 */
function rgba2arr(color, normalized = true) {
  console.log("color", color);
  let ret: any = [];
  let colorStr = new RegExp(/(?<=\()\S+(?=\))/).exec(color);
  // console.log("colorStr",colorStr);
  if (colorStr) {
    ret = colorStr[0].split(",");
    if (ret.length < 4) ret.push(1);
    ret = ret.map(item => {
      return Number.parseFloat(item);
    });
  }

  if (normalized) {
    ret = ret.map((item, index) => {
      if (index != 3) //rgba
        return (item = +item / 255);
      else
        return item
    });

  }
  return ret;
}




/**
 * 新增
 */
function add() {
  edit({});
}

/**
 * 编辑
 */
function edit(record) {
  nextTick(() => {
    resetFields();
    //赋值
    Object.assign(formData, record);
    if (formData.color) {
      let color = formData.color
      color = color.replace("[", '')
      color = color.replace("]", '')
      color = color.split(",")
      pureColor.value = { "r": color[0] * 255, "g": color[1] * 255, "b": color[2] * 255, "a": color[3] }
    }
    if (formData.intervalColor) {
      let color = formData.intervalColor
      color = color.replace("[", '')
      color = color.replace("]", '')
      color = color.split(",")
      intervalColor.value = { "r": color[0] * 255, "g": color[1] * 255, "b": color[2] * 255, "a": color[3] }
    }
  });
}

/**
 * 提交数据
 */
async function submitForm() {
  // 触发表单验证
  await validate();
  confirmLoading.value = true;
  const isUpdate = ref<boolean>(false);
  //时间格式化
  let model = formData;
  if (model.id) {
    isUpdate.value = true;
  }
  //循环数据
  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(',');
      }
    }
  }
  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>
