<template>
  <div v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)" class="simpleQuery">
    <el-form ref="ruleForm" inline :model="tableForm">
      <el-form-item v-for="(item, index) in formItemArr" :key=" index" :rules="fromDataReq(item)" :prop="item.pagecode">
        <template v-if="fromDataType(item.datatype) == 'SELECT' || fromDataType(item.datatype) == 'SELECTS'">
          <el-select class="input-shadow" size="small" :style="{'width':item.displaywidth ? item.displaywidth+'px':''}" :disabled="item.disabled ? item.disabled : false" :multiple="fromDataType(item.datatype) == 'SELECTS'?true:false" filterable default-first-option style="width: 100%" v-model="tableForm[item.pagecode]" @change="changeSelect(item.pagecode, tableForm[item.pagecode])" :placeholder="item.pagename" clearable @clear="tableForm[item.pagecode] = ''">
            <el-option v-for="(itemParams,sindex) in tableOptions[item.pagecode]" :key="itemParams[item['dropdownlistid']]+sindex" :label="itemParams[item['dropdownlistlabel']]" :value="itemParams[item['dropdownlistid']]">
            </el-option>
          </el-select>
        </template>
        <template v-else-if="fromDataType(item.datatype) == 'DROP'">
          <el-select class="input-shadow" size="small" multiple filterable default-first-option style="width: 100%" v-model="tableForm[item.pagecode]" @change="changeSelect(item.pagecode, item)" :style="{'width':item.displaywidth ? item.displaywidth+'px':''}" :placeholder="'请选择'+item.pagename" clearable @clear="tableForm[item.pagecode] = ''">
            <el-option v-for="itemParams in tableOptions[item.pagecode]" :key="itemParams['dropdownlistid']" :label="itemParams['dropdownlistlabel']" :value="itemParams['dropdownlistid']">
            </el-option>
          </el-select>
        </template>
        <template v-else-if="fromDataType(item.datatype) == 'ICON' || fromDataType(item.datatype) == 'icon'">
          <el-select size="small" clearable v-model="tableForm[item.pagecode]" placeholder="请选择图标">
            <el-option v-for="(item,index) in formIcons" :key="index" :label="item.name" :value="item.value">
              <i style="font-size: 18px;" :class="item.name"></i>
            </el-option>
          </el-select>
        </template>
        <template v-else-if="fromDataType(item.datatype) == 'TEXT' || fromDataType(item.datatype) == 'VARCHAR'">
          <el-input size="small" clearable :style="{'width':item.displaywidth ? item.displaywidth+'px':''}" :placeholder="'请输入'+item.pagename" @change="inputChangeHandler(item.pagecode)" v-model="tableForm[item.pagecode]"></el-input>
        </template>
        <template v-else-if="fromDataType(item.datatype) == 'TEXTAREA'">
          <el-input type="textarea" :style="{'width':item.displaywidth ? item.displaywidth+'px':''}" clearable v-model="tableForm[item.pagecode]"></el-input>
        </template>
        <template v-else-if="fromDataType(item.datatype) == 'PASSWORD'">
          <el-input show-password v-model="tableForm[item.pagecode]"></el-input>
        </template>
        <template v-else-if="fromDataType(item.datatype) == 'UNPASSWORD'">
          <el-input show-password v-model="tableForm[item.pagecode]"></el-input>
        </template>
        <template v-else-if="fromDataType(item.datatype) == 'UPLOAD'">
          <upload-item :id="index" :base-img="tableForm[item.pagecode]" ref="upload" />
        </template>
        <template v-else-if="fromDataType(item.datatype) == 'SWITCH'">
          <el-switch v-model="tableForm[item.pagecode]"></el-switch>
        </template>
        <template v-else-if="fromDataType(item.datatype) == 'CASCADER'">
          <el-cascader v-model="tableForm[item.pagecode]" :options="tableOptions[item.pagecode]"></el-cascader>
        </template>
        <template v-else-if="fromDataType(item.datatype) == 'CHECKBOX'">
          <el-checkbox-group v-model="tableForm[item.pagecode]">
            <el-checkbox v-for="itemParams in tableOptions[item.pagecode]" :key="itemParams[item['dropdownlistid']]" :label="itemParams[item['dropdownlistid']]" name="type">{{ [item['dropdownlistlabel']] }}</el-checkbox>
          </el-checkbox-group>
        </template>
        <template v-else-if="fromDataType(item.datatype) == 'RADIO'">
          <el-radio-group v-model="tableForm[item.pagecode]">
            <el-radio v-for="itemParams in tableOptions[item.pagecode]" :key="itemParams[item['dropdownlistid']]" :label="itemParams[item['dropdownlistid']]" name="type">{{ [item['dropdownlistlabel']] }}</el-radio>
          </el-radio-group>
        </template>
        <template v-else-if="fromDataType(item.datatype) == 'TIME'">
          <el-time-picker size="small" :picker-options="{selectableRange: '00:00:00 - 23:59:59'}" v-model="tableForm[item.pagecode]" placeholder="选择任意时间段" @change="inputChangeHandler(item.pagecode)">
          </el-time-picker>
        </template>
        <template v-else-if="fromDataType(item.datatype) == 'DATE'">
          <el-date-picker size="small" :style="{'width':item.displaywidth ? item.displaywidth+'px':''}" class="datetimes" value-format="yyyy-MM-dd" v-model="tableForm[item.pagecode]" type="date" placeholder="选择日期" @change="inputChangeHandler(item.pagecode)">
          </el-date-picker>
        </template>
        <template v-else-if="fromDataType(item.datatype) == 'DATETIME'">
          <el-date-picker size="small" :style="{'width':item.displaywidth ? item.displaywidth+'px':''}" class="datetimes" value-format="yyyy-MM-dd HH:mm:ss" v-model="tableForm[item.pagecode]" type="datetime" placeholder="选择日期时间" @change="inputChangeHandler(item.pagecode)">
          </el-date-picker>
        </template>
        <template v-else-if="fromDataType(item.datatype) == 'INT' || fromDataType(item.datatype) == 'tinyint' || fromDataType(item.datatype) == 'NUMBER'">
          <el-input size="small" :style="{'width':item.displaywidth ? item.displaywidth+'px':''}" v-model.number="tableForm[item.pagecode]" onkeyup="value=value.replace(/[^1-9]/g,'')" @change="inputChangeHandler(item.pagecode)"></el-input>
        </template>
        <template v-else>
          <el-input size="small" :style="{'width':item.displaywidth ? item.displaywidth+'px':''}" :placeholder="'请输入'+item.pagename" v-model="tableForm[item.pagecode]" @change="inputChangeHandler(item.pagecode)"></el-input>
        </template>
      </el-form-item>
      <el-form-item>
        <!-- <el-button size="small" @click="restSubmit" type="warning">重置</el-button> -->
        <el-button size="small" type="primary" @click="onSubmit">查询</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import PublicPageForm from '@/components/publicPageForm'
import { Query } from "@/api/webApi"

export default {
  name: 'SimpleQuery',
  props: {
    simpleQueryItem: {
      type: Array,
      default: () => new Array()
    },
    selectOptions: {
      type: Array,
      default: () => new Array()
    },
  },
  components: { PublicPageForm },
  data () {
    return {
      loading: false,
      tableForm: {},
      tableOptions: {},
      queryContent: {},
      formItemArr: []
    }
  },
  computed: {
    //设置新增修改表单类型
    fromDataType () {
      return function (type) {
        if (type) {
          return type.toLocaleUpperCase().replace(/\([^\)]*\)/g, "");
        }
      }
    },
    //设置新增修改表单必填类型
    fromDataReq () {
      return function (item) {
        const { dropdownlist, datatype, pagename, isrequired, formatrule } = item
        const itemType = datatype.replace(/\([^\)]*\)/g, "")
        const itemReq = isrequired ? true : false
        const itemRule = formatrule ? true : false
        if (dropdownlist || dropdownlist == 0) return [{ required: itemReq, message: `${pagename}不能为空`, trigger: 'change' }]
        else if (itemType == 'date' || itemType == 'datetime') return [{ required: itemReq, message: `${pagename}不能为空`, trigger: 'change' }]
        else
          if (itemReq && itemRule) return [{ required: itemReq, message: `${pagename}不能为空`, trigger: 'blur' }, { pattern: new RegExp(formatrule), message: `请输入合法的${pagename}规则`, trigger: 'blur' }]
        return [{ required: itemReq, message: `${pagename}不能为空`, trigger: 'blur' }]
      }
    },
  },
  watch: {
    simpleQueryItem: {
      handler (array) {
        this.getSelectData(array)
      },
      deep: true,
      immediate: true
    },
    selectOptions: {
      handler (array) {
        this.formatForm(array)
      },
      deep: true,
      immediate: true
    },
  },
  methods: {
    onSubmit () {
      try {
        this.$refs['ruleForm'].validate(valid => {
          if (!valid) {
            throw new Error()
          }
        })
        const queryContent = []
        const params = this.tableForm
        for (const key in params) {
          if (Object.hasOwnProperty.call(params, key)) {
            const value = params[key]
            if (value) {
              const obj = {
                column: key,
                comparator: '=',
                value,
                connector: '',
                left: '(',
                right: ')'
              }
              queryContent.push(obj)
            }
          }
        }
        this.queryContent = queryContent
        this.$emit('queryValue', this.queryContent)
      } catch (error) {
        error.message && this.$message.error(error.message)
      }
    },
    restSubmit () {
      const tableForm = {}
      this.tableForm = tableForm
    },
    sendColData () {
      this.$emit('queryValue', this.queryContent)
    },
    //获取表单下拉数据
    changeSelect (code, data) {
      this.$emit('changeSelect', data)
      if (code == 'passparameters') return
      const datas = this.$store.state.auth.authMsg
      if (!datas?.length) return
      const ndata = datas.filter(item => item.labelcode && item.pagecode == code)
      if (ndata?.length) {
        const nitem = ndata[0]
        const nval = this.tableForm[code]
        const { dropdownlistlabel, labelcode, dropdownlistid } = nitem
        const wdata = this.tableOptions[code].filter(item => item[dropdownlistid] == nval)
        if (!wdata.length) return
        const witem = wdata[0]
        this.tableForm[labelcode] = witem[dropdownlistlabel]
      }
    },
    inputChangeHandler (data) {
      if (!this.tableForm[data]) this.tableForm[data] = null
    },
    //格式化传递参数数据
    formatDefault (item) {
      if (typeof item != 'string') return {}
      const filterItem = {}
      const parameters = item.replace('{', '').replace('}', '')
      const parametersSplit = parameters?.split(',')
      parametersSplit.map(item => {
        const [key, val] = item?.split(':')
        filterItem[key] = val
      })
      return filterItem
    },
    getSelectData (formItem) {
      if (!formItem.length || !Array.isArray(formItem)) return
      const formItemCopy = _.cloneDeep(formItem)
      const results = []
      const resultsKey = []
      formItemCopy.map(({ dropdownlist, pagecode, defaultparameters }) => {
        if (((dropdownlist || dropdownlist == 0) && dropdownlist != "")) {
          const datacontent = defaultparameters ? { filter: this.formatDefault(defaultparameters) } : { filter: { 1: 1 } }
          results.push(Query({ serviceid: dropdownlist, datacontent, event: '0', page: 1, size: 9999 }))
          resultsKey.push(pagecode)
        }
      })
      if (results?.length) {
        this.getAnscyData(resultsKey, results, formItemCopy)
      } else {
        this.formItemArr = formItemCopy
      }
    },
    //获取异步数据
    async getAnscyData (allResultKey, allResult, formItem) {
      this.loading = true
      const results = await Promise.allSettled(allResult)
      results.map((item, index) => {
        const { status, value } = item
        if (status == 'fulfilled') {
          const { code, returnData } = value
          this.tableOptions[allResultKey[index]] = code == 0 && returnData?.length ? this.formatData(returnData) : []
        }
      })
      this.formItemArr = formItem
      this.loading = false
    },
    formatData (returnData) {
      return typeof returnData == 'string' ? JSON.parse(returnData) : returnData
    },
    formatForm (array) {
      if (!array.length) return
      const ndatas = [...array]
      const tableForm = {}
      ndatas.forEach(item => {
        const { column, value } = item
        if (value) {
          tableForm[column] = value
        }
      })
      this.tableForm = tableForm
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep.simpleQuery {
  .el-scrollbar__wrap {
    overflow-x: auto;
  }
  .is-vertical {
    display: none;
  }
  .el-select {
    width: 100%;
  }
}
</style>