<template>
  <dlg
      :dlgTitle="props.dlgTitle"
      :dlgWidth="props.dlgParams.dlgWidth"
      :dlgHeight="props.dlgParams.dlgHeight"
      @dlgConfirm="handleDlgConfirm"
      @dlgCancel="handleDlgCancel"
  >
    <template #dlg-content-slot>
      <a-layout style="height: 100%" v-if="state.ifShow" v-loading="props.dlgLoading">
        <a-layout-content
            style="padding: 5px; border: 1px solid #d1dbe5; "
        >
          <Card
              style="padding: 0px; height: 100%"
              :body-style="{
            padding: '0px',
            borderRadius: '0px',
          }"
          >
            <lt-a-form>
              <a-form
                  ref="formRef"
                  :model="state.formData"
                  autocomplete="off"
                  :label-col="{ flex: props.dlgParams.labelWidth?props.dlgParams.labelWidth:'100px' }"
                  style="width: 100%"
                  :rules="state.rules"
                  @finish="handleFinish"
                  @finishFailed="handleFinishFailed"
              >
                <a-row v-for="(item, index) in props.dlgParams.formCols" :key="index">
                  <a-col v-for="item2 in item" :key="item2.Field" :span="item2.Span">
                    <a-tooltip :key="item2.Field" :title="state.validTips[item2.Field]" color="#ff5154">
                      <a-form-item
                          :colon="false"
                          :label="item2.title"
                          :name="item2.Field"
                          :has-feedback="true"
                      >

                        <a-select
                            v-if="item2.Style === 'ComBox'"
                            v-model:value="state.formData[item2.Field]"
                            :disabled="!isEdit(item2,state.formData)"
                            :show-search="true"
                            allowClear
                            @change="handleComBoxChange(item2,$event)"
                        >
                          <a-select-option
                              v-for="el in item2.Option"
                              :value="el.value"
                              :key="el.value"
                          >{{ el.label }}
                          </a-select-option
                          >
                        </a-select>
                        <a-checkbox
                            v-else-if="item2.Style === 'CheckBox'"
                            :disabled="!isEdit(item2,state.formData)"
                            v-model:checked="state.formData[item2.Field]"
                            @change="handleCheckBoxDataChange(item2,$event)"
                        ></a-checkbox>
                        <a-input
                            v-else-if="item2.Style === 'NumberBox'"
                            v-model:value="state.formData[item2.Field]"
                            @change="handleNumberInputChange(item2,false,$event)"
                        ></a-input>
                        <a-input
                            v-else-if="item2.Style === 'FloatNumberBox'"
                            v-model:value="state.formData[item2.Field]"
                            @change="handleNumberInputChange(item2,true,$event)"
                        ></a-input>
                        <a-date-picker
                            v-else-if="item2.Style === 'Date'"
                            allowClear
                            size="small"
                            valueFormat="YYYY-MM-DD"
                            :disabled="!isEdit(item2,state.formData)"
                            v-model:value="state.formData[item2.Field]" />
                        <a-date-picker
                            v-else-if="item2.Style === 'DateTime'"
                            format="YYYY-MM-DD HH:mm:ss"
                            :disabled="!isEdit(item2,state.formData)"
                            allowClear
                            :show-time="true"
                            :value="setDayjs(state.formData[item2.Field])"
                            size="small"
                            @change="(value:Dayjs,dateString:string)=>handleDateTimeChange(item2,value,dateString)"
                        />
                        <a-tree-select
                            v-else-if="item2.Style === 'Tree'"
                            v-model:value="state.formData[item2.Field]"
                            show-search
                            style="width: 100%"
                            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                            :placeholder="locale.value==='zh'?'请选择':'Please select'"
                            allow-clear
                            size="small"
                            tree-default-expand-all
                            :tree-data="item2.treeOption"
                            tree-node-filter-prop="label"
                            @change="(value, label, extra)=>handleTreeDataChange(item2,value)"
                            :dropdownMatchSelectWidth="true"
                        >
                        </a-tree-select>
                        <div v-else-if="item2.Style === 'SelectBox'" style="display: flex;align-items: center;width: 100%;height: 32px;"
                        >
                          <span style="display:inline-block;width: 100%;border-radius: 5px 0 0 5px;border:0px solid #d1dbe5;">{{state.formData[item2.Field]}}</span>
                          <a-button v-if="isEdit(item2,state.formData)" type=""  style="width: 50px;margin:0" @click="handleSelectBox(item2)">
                            <template #icon>
                              <i class="icon icon-search" style="color:#4687ef"> </i>
                            </template>
                          </a-button>
                        </div>
                        <a-textarea v-else-if="item2.Style === 'TextArea'" :disabled="!isEdit(item2,state.formData)" v-model:value="state.formData[item2.Field]"
                                    allowClear :showCount="false" :autosize="{ minRows: 4, maxRows: 6 }"/>
                        <a-input
                            v-else-if="isEdit(item2,state.formData)"
                            v-model:value="state.formData[item2.Field]"
                            allow-clear
                            @change="handleTextInputChange(item2,$event)"
                        ></a-input>
                        <span
                            v-else
                        >{{ state.formData[item2.Field] }}</span>
                      </a-form-item>
                    </a-tooltip>
                  </a-col>
                </a-row>
              </a-form>
            </lt-a-form>
          </Card>
        </a-layout-content>
      </a-layout>
    </template>
    <template #dlg-footer>
      <div style="display: flex;justify-content: center;padding-top: 5px;" v-if="props.ifShowPrint">
        <a-button type="primary" v-if="true" @click="handlePreview">
          {{ $t("Formula.Common.Preview") }}
        </a-button>
        <a-button type="primary" v-if="true" @click="handleExport">
          {{ $t("Formula.Common.Export") }}
        </a-button>
        <a-button v-if="true" @click="handleDlgCancel" >
            {{ $t("Formula.Common.Cancel") }}
          </a-button>
      </div>
    </template>
  </dlg>
</template>

<script lang="ts" setup>
import Dlg from "./dlg.vue"
import {cloneDeep} from "lodash-es";
import {ref, PropType, onMounted, computed, unref, reactive, onBeforeMount, nextTick} from "vue"
import {Card, message} from "ant-design-vue";
import CommonForm from "../lt-common-form/common-form.vue"
import {useI18n} from "vue-i18n";
import {ColInter, DlgFormParamsInter} from "@/utils/common-type";
import {isNull} from "@/utils/is";
import Vue from 'vue'
import dayjs, {Dayjs} from "dayjs";
import FormTree from "@/views/common-component/lt-common-tree/form-tree.vue";
import {checkNull} from "@/hooks/useCommonMethods";

const emits = defineEmits(['dlgConfirm', 'dlgCancel',"showSelectBoxDlg","dataChange","Preview","Export"])
const {locale,t} = useI18n()

const props = defineProps({
  sendData: {
    type: Object,
    default() {
      return {}
    }
  },
  dlgTitle: {
    type: String,
    default: "弹窗名称"
  },
  editType: {
    type: String,
    default: "add"
  },
  dlgLoading:{
    type:Boolean,
    default:false
  },
  dlgParams: {
    type: Object as PropType<DlgFormParamsInter>,
    default() {
      return {
        dlgWidth: {
          type: String,
          default: "600px"
        },
        dlgHeight: {
          type: String,
          default: "300px"
        },
        dataStruct: {},
        formCols: [],
        labelWidth: 100,
        rules: {},
        customEdit:(col:ColInter,formData:any)=>{
          return col.isEdit
        }
      }
    }
  },
  ifShowPrint:{
    type:Boolean,
    default:false
  }
})

const state = reactive({
  ifShow: false,
  formData: {} as any,
  rules: {},
  dataStruct: {},
  validTips: {} as any
})
const formRef = ref(null)

const handleDlgConfirm = () => {
  formRef.value.validateFields().then(() => {
    for (let key in state.dataStruct) {
      state.validTips[key] = ''
    }
    emits('dlgConfirm',state.formData)
  }).catch((err: any) => {
    for (let key in state.dataStruct) {
      state.validTips[key] = ''
    }
    for (let i = 0; i < err.errorFields.length; i++) {
      state.validTips[err.errorFields[i].name[0]] = err.errorFields[i].errors[0]
    }
    message.warning(t(('Formula.Common.PleaseCheckForm')))
  })
}
const handleDlgCancel = () => {
  emits('dlgCancel')
}
const handlePreview=()=>{
  emits('Preview')
}
const handleExport=()=>{
  emits('Export')
}
const _initParams = () => {
  for (let key in props.dlgParams) {
    if (state[key] !== undefined) {
      state[key] = props.dlgParams[key]
    }
  }
}
const _initForm = function () {
  state.dataStruct = cloneDeep(props.dlgParams.dataStruct)
  for (let key in state.dataStruct) {
    state.validTips[key] = ''
  }
  state.formData = cloneDeep(props.dlgParams.dataStruct)
  if (props.editType === 'edit') {
    state.formData = cloneDeep(props.sendData)
  }
  nextTick(() => {
    state.ifShow = true
  })
};
const filterOption = (input: string, option: any) => {
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};
const handleComBoxChange = (col: ColInter, value: string | number) => {
  if (!checkNull(value)) {
    if (col.Relation) {
      let item = col.Option.find((item) => item.value == value);
      for (let key in col.Relation) {
        state.formData[key] = item[col.Relation[key]];
      }
    }
  } else {
    for (let key in col.Relation) {
      state.formData[key] = null;
    }
  }
  emits('dataChange',col,state.formData)
}
/*const handleNumberInputChange=(col: ColInter,ifFloat:boolean, e: any)=>{
  let value=null
  //e是个事件，每次只能获得当前按下的字符，感觉有点弱智
  if (checkNull(state.formData[col.Field])) {
    state.formData[col.Field] = null;
  } else {
    if (ifFloat) {
      //限制只能输入数字
      value=state.formData[col.Field].toString().replace(/[^\-\d.]/g, "")
      if(value!=='-'&&value){
        value = Number(value)
      }
    } else {
      //限制只能输入数字，小数点都不要了
      value=state.formData[col.Field].toString().replace(/[^\-\d]/g, "")
      // debugger
      if(value!=='-'&&value){
        value = Number(value)
      }
    }
    state.formData.Amount = value;
  }
}*/
const handleTextInputChange = (col: ColInter, e: any) => {
  emits('dataChange',col,state.formData)
}
const handleCheckBoxDataChange = (col:ColInter, e: any)=>{
  emits('dataChange',col,state.formData)
}
const handleNumberInputChange= (col:ColInter,ifFloat:boolean, e: any)=>{
  if(ifFloat){
    nextTick(()=>{
      state.formData[col.Field] = state.formData[col.Field].replace(/[^\d.]/g, "");
      emits('dataChange',col,state.formData)
    })
  }else{
    nextTick(()=>{
      state.formData[col.Field] = state.formData[col.Field].replace(/[^\d]/g, "");
      emits('dataChange',col,state.formData)
    })
  }
}
const handleFinish = (value: any) => {
  emits('dlgConfirm')
}
const handleFinishFailed = (errInfo: any) => {
  console.log(errInfo)
}
const handleSelectBox=(col: ColInter)=>{
  emits('showSelectBoxDlg',col,state.formData)
}
const isEdit=(col:ColInter,formData:any)=>{
  if(props.dlgParams.customEdit){
    return props.dlgParams.customEdit(col,formData)
  }
  return col.isEdit
}
const handleDateTimeChange=(col:ColInter,value: Dayjs, dateString: string)=>{
  state.formData[col.Field]=dateString
}
const setDayjs=(dateValue:string)=>{
  if(dateValue){
    return dayjs(dateValue)
  }
  return ''
}
const handleTreeDataChange=(col:ColInter,value:string)=>{
  emits('dataChange',col,state.formData)
}

onBeforeMount(() => {
  _initParams()
  _initForm();
})
onMounted(() => {

});
</script>

<style scoped>

</style>