<template>
  <el-form :inline="inline"
           v-model="query"
           @submit.native.prevent>
    <template v-for="item in customFields">
      <template v-if="item.stable&&item.show">
        <el-form-item :key="item.title">
          <template v-if="item.type===0">
            <ExtRender
                class="z-w150"
                :render-func="item.render"/>
          </template>
          <template v-if="item.type===1||item.type===2">
            <Input
                class="z-w150"
                :placeholder="item.title"
                v-model.trim="query[item.key]"
                @on-change="handleQuery"
                @keyup.enter.native="handleQuery"/>
          </template>
          <template v-else-if="item.type===3">
            <ExtSelect
                v-if="item.url"
                :clearable="true"
                class="z-w150"
                :placeholder="item.title"
                :url="item.url"
                :query="item.query"
                v-model="query[item.key]"
                @on-change="handleQuery"/>
            <ExtDSelect
                v-else-if="item.dict"
                class="z-w150"
                :multiple="true"
                :dicts="item.dicts"
                :placeholder="item.title"
                v-model.trim="query[item.key+'inList']"
                @change="handleQuery"
                :type="item.dict"/>
            <ExtBoolean
                v-else-if="item.boolean"
                class="z-w150"
                v-model="query[item.key]"
                :placeholder="item.title"/>
            <ExtInputNumber
                v-else-if="item.ratio"
                class="z-w150"
                :ratio="item.ratio"
                :placeholder="item.title"
                v-model.trim="query[item.key]"
                @on-change="handleQuery"
                @keyup.enter.native="handleQuery"/>
            <Input
                v-else
                type="number"
                class="z-w150"
                :placeholder="item.title"
                v-model.trim="query[item.key]"
                @on-change="handleQuery"
                @keyup.enter.native="handleQuery"/>
          </template>
          <template v-else-if="item.type===4||item.type===5">
            <ExtDSelect
                class="z-w150"
                :multiple="true"
                :dicts="item.dicts"
                :placeholder="item.title"
                v-model.trim="query[item.key+'inList']"
                @change="handleQuery"
                :type="item.dict"/>
          </template>
          <template v-else-if="item.type===6||item.type===7||item.type===8">
          </template>
          <template v-else-if="item.type===9">
            <ExtTreeSelect
                v-model.trim="query[item.key+'inList']"
                :placeholder="item.title"
                :tree-url="item.url"
                :clearable="true"/>
          </template>
          <template v-else-if="item.type===10">
            <ExtTreeSelect
                v-model.trim="query[item.key+'inList']"
                class="z-w150"
                :placeholder="item.title"
                :tree-url="item.url"
                tree-type="account"
                :clearable="true"/>
          </template>
          <template v-else-if="item.type===11">
            <ExtDatePicker
                class="z-w150"
                :placeholder="item.title"
                v-model="query[item.key]"
                type="date"
                @on-change="handleQuery"/>
          </template>
          <template v-else-if="item.type===12">
            <ExtDatePicker
                class="z-w300"
                :placeholder="item.title"
                v-model="query"
                type="datetimerange"
                :fields="item.key"
                @range-change="handleQuery"/>
          </template>
          <template v-else>无匹配</template>
        </el-form-item>
      </template>

    </template>
  </el-form>
</template>

<script setup lang="ts" name="ExtQuerySection">
import {reactive, onMounted, computed} from 'vue';
import {Local} from "/@/utils/storage";
import u from "/@/utils/u"


const props = defineProps({
  columns: {
    type: Array,
    default: () => {
      return []
    }
  },
  inline: {
    type: Boolean,
    default: true
  },
  formQuery: {
    type: Object,
  },
  hasOptions: {
    type: Boolean,
    default: false
  },
  name: {
    type: String
  }
})

const state = reactive({
  customFields: [] as Array<QueryField>,
  defaultCustom: ["id", "name", "title", "status", "type", "createBy", "updateBy", "createAt", "updateAt"]
});

// 定义子组件向父组件传值/事件
const emit = defineEmits(['on-fields-change', 'on-query-change']);

//computed
const query = computed({
  get: () => props.formQuery,
  set: (val: any) => {
    emit("on-query-change", val);
  }
});
/*watch(
    () => props.query,
    () => {
      // initModeValueEcho();
      // initFontIconName();
    }
);*/
const saveCustomQuery = () => {
  Local.set(`${props.name}_custom_query`, state.customFields);
}
const loadCustomQuery = (): Array<any> => {
  return Local.get(`${props.name}_custom_query`);
}
const setupCustomFields = (reset: Boolean = false) => {
  let cacheCustomQuery = loadCustomQuery();
  let icolumns = (<QueryFields>props.columns).filter((k: QueryField) => !!k.key && k.query);
  // console.table(icolumns, "title", "key")
  //<!--  public static final int FIELD_文本 = 1;-->
  //<!--  public static final int FIELD_文本域 = 2;-->
  //<!--  public static final int FIELD_数字 = 3;-->
  //<!--  public static final int FIELD_单选 = 4;-->
  //<!--  public static final int FIELD_复选 = 5;-->
  //<!--  public static final int FIELD_富文本 = 6;-->
  //<!--  public static final int FIELD_图片 = 7;-->
  //<!--  public static final int FIELD_附件 = 8;-->
  //<!--  public static final int FIELD_部门选择 = 9;-->
  //<!--  public static final int FIELD_成员选择 = 10;-->
  //<!--  public static final int FIELD_日期选择 = 11;-->
  //<!--  public static final int FIELD_日期范围选择 = 12;-->
  if (reset) {
    let tmp: Array<QueryField> = [];
    //1.先取默认固定字段
    state.defaultCustom.forEach(custom => {
      let index = icolumns.findIndex(k => k.key === custom);
      if (index >= 0) {
        let field = icolumns[index];
        if (field.hasOwnProperty("key")) {
          let {key, type, name, title, dict, url, query, boolean} = field;
          let obj = {
            key: key,
            name: name,
            title: title,
            type: type,
            dict: dict, //字典
            url: url,
            query: query,
            boolean: boolean,
            show: true,
            stable: true
          }
          if (cacheCustomQuery) {
            let _t = cacheCustomQuery.find(k => k.key === key);
            if (_t) {
              obj = Object.assign({}, obj, _t);
            }
          }
          tmp.push(obj);
        }
      }
    })
    //2.再取系统字段
    icolumns.forEach(column => {
      if (!state.defaultCustom.includes(column.key)) {
        let {key, type, name, title, dict, url, query, boolean} = column;
        let obj = {
          key: key,
          name: name,
          title: title,
          type: type,
          dict: dict, //字典
          url: url,
          query: query,
          boolean: boolean,
          show: true,
          stable: false
        }
        if (cacheCustomQuery) {
          let _t = cacheCustomQuery.find(k => k.key === key);
          if (_t) {
            obj = Object.assign({}, obj, _t);
          }
        }
        tmp.push(obj);
      }
    })
    //排序
    if (!u.isEmptyOrNull(cacheCustomQuery)) {
      let sortArray = cacheCustomQuery.map(k => k.key);
      u.sortByArray(tmp, 'key', sortArray)
    }
    state.customFields = tmp;
  } else {
    let hasInit = !!cacheCustomQuery;
    if (!hasInit) {
      let tmp: Array<QueryField> = [];
      icolumns.forEach(column => {
        let {key, type, name, title, dict, url, query} = column;
        tmp.push({
          key: key,
          name: name,
          title: title,
          type: type,
          dict: dict,
          url: url,
          query: query,
          show: true,
          stable: state.defaultCustom.includes(column.key),
        });
      })
      state.customFields = tmp;
    } else {
      state.customFields = icolumns;
    }
  }
  emit("on-fields-change", state.customFields);
  saveCustomQuery();
  console.log("----->", JSON.stringify(state.customFields))

}

const handleQuery = () => {
  emit("on-query-change", props.query);
}
const handleFieldShowChange = (show: boolean, idx: number) => {
  state.customFields[idx].show = show;
  emit("on-fields-change", state.customFields);
  saveCustomQuery();
}
const handleMoveSort = () => {
  saveCustomQuery();
  return true;
}

const handleResetCustomFields = () => {
  removeCustomQuery();
  setupCustomFields(true);
}

const removeCustomQuery = () => {
  Local.remove(`${props.name}_custom_query`)
}

onMounted(() => {
  setupCustomFields(true)
});
</script>


<style scoped lang="less">
.popup-item-name {
  cursor: all-scroll;
  padding: 5px;
}

.actived {
  color: #00C7D2;
}

.inline-form {
  display: flex;
  width: 450px;
  flex-wrap: wrap;
  justify-content: space-between;
}
</style>
