<template>
  <div v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)" class="PublicPageForm">
    <el-form ref="ruleForm" :model="tableForm" :label-width="labelWidth">
      <el-row :gutter="20">
        <el-col v-for="(item, index) in formItemArr" :key=" index" :span="formType == 'horizontal' ? formSpan : 24" v-show="isShow(item.isdisplay)">
          <el-form-item :rules="fromDataReq(item)" :prop="item.pagecode" :label="item.pagename">
            <template v-if="fromDataType(item.datatype) == 'SELECT' || fromDataType(item.datatype) == 'SELECTS'">
              <el-select class="input-shadow" size="small" :multiple="fromDataType(item.datatype) == 'SELECTS'?true:false" filterable default-first-option style="width: 100%" v-model="tableForm[item.pagecode]" @change="changeSelect(item.pagecode, item)" placeholder="请选择" clearable @clear="tableForm[item.pagecode] = ''">
                <el-option v-for="itemParams in tableOptions[item.pagecode]" :key="itemParams[item['dropdownlistid']]" :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)" placeholder="请选择" 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) == 'TEXT' || fromDataType(item.datatype) == 'VARCHAR'">
              <el-input size="small" @change="inputChangeHandler(item.pagecode)" v-model="tableForm[item.pagecode]"></el-input>
            </template>
            <template v-else-if="fromDataType(item.datatype) == 'TEXTAREA'">
              <el-input type="textarea" 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) == 'UPLOAD'">
              <upload :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 :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 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 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" 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" v-model="tableForm[item.pagecode]" @change="inputChangeHandler(item.pagecode)"></el-input>
            </template>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { Query } from "@/api/webApi"
import Upload from './upload.vue'
import JSEncrypt from "jsencrypt"
export default {
  name: 'PublicPageForm',
  components: { Upload },
  props: {
    formType: {
      type: String,
      default: 'vertical' //horizontal--水平布局 默认一行3列
    },
    formItem: {
      type: Array,
      default: () => new Array()
    },
    formPass: {
      type: Array,
      default: () => new Array()
    },
    formData: {
      type: Object,
      default: () => new Object()
    },
    formSpan: {
      type: Number,
      default: 8
    },
    formType: {
      type: String,
      default: 'add'
    },
    labelWidth: {
      type: String,
      default: '80px'
    }
  },
  data () {
    return {
      tableForm: {},
      tableOptions: {},
      formItemArr: [],
      loading: false
    }
  },
  watch: {
    formItem: {
      handler (array) {
        this.getSelectData(array)
      },
      deep: true,
      immediate: true
    },
    formData: {
      handler (obj) {
        if (!Object.keys(obj).length) {
          const nload = this.formItemArr.filter(item => item.datatype == 'upload' || item.datatype == 'UPLOAD')
          if (nload?.length) this.clearTypeUpload(nload)
        }
        this.tableForm = obj
      },
      deep: true,
      immediate: true
    }
  },
  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, type: 'date', 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' }]
      }
    },
  },
  methods: {
    //格式化传递参数数据
    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 [allResult, allResultKey] = [[], []]
      formItemCopy.map(({ dropdownlist, pagecode, defaultparameters }) => {
        if (((dropdownlist || dropdownlist == 0) && dropdownlist != "")) {
          const datacontent = defaultparameters ? { filter: this.formatDefault(defaultparameters) } : { filter: { 1: 1 } }
          allResultKey.push(pagecode)
          allResult.push(Query({ serviceid: dropdownlist, datacontent, event: '0' }))
        }
      })
      this.getAnscyData(allResultKey, allResult, _.cloneDeep(formItem))
    },
    //获取异步数据
    async getAnscyData (allResultKey = [], allResult = [], formItem = []) {
      this.loading = true
      if (allResult.length && allResultKey.length) {
        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
      } else {
        this.formItemArr = formItem
      }
      const passitem = this.formItemArr.filter(item => item.pagecode == 'passparameters')
      if (passitem?.length) {
        const passitemkey = passitem[0]
        passitemkey.datatype = 'DROP'
        this.formPass.map(item => {
          item.dropdownlistid = item.pageconfigurationid
          item.dropdownlistlabel = item.pagename
        })
        this.tableOptions['passparameters'] = this.formPass.length ? this.formPass : ''
      }
      this.loading = false
    },
    formatData (returnData) {
      return typeof returnData == 'string' ? JSON.parse(returnData) : returnData
    },
    //设置下拉数据
    formatSelectData () {

    },
    //获取表单下拉数据
    changeSelect (code, item) { },
    inputChangeHandler (data) {
      if (!this.tableForm[data]) this.tableForm[data] = null
    },
    restForm () {
      this.$refs['ruleForm'].resetFields()
    },
    addTypePassWord (ndata = []) {
      if (ndata?.length) {
        const pubKeyStr = sessionStorage.getItem('pubKeyStr')
        if (!pubKeyStr) return
        ndata.map(({ pagecode }) => {
          const jse = new JSEncrypt()
          jse.setPublicKey(pubKeyStr)
          this.tableForm[pagecode] = jse.encrypt(this.tableForm[pagecode].replace(/\s+/g, ""))
        })
      }
    },
    addTypeUpload (nload = []) {
      if (nload?.length) {
        const files = this.$refs['upload']
        files.map((item, index) => {
          this.tableForm[nload[index]['pagecode']] = item.imageUrl
        })
      }
    },
    formatPass (npass = []) {
      const datas = []
      const maps = []
      if (Array.isArray(npass) && npass?.length) {
        this.formPass.filter(item => {
          npass.map(p => {
            if (item.dropdownlistid == p) {
              datas.push(item)
            }
          })
        })
      }
      if (datas?.length) {
        datas.map(item => {
          const nitem = {}
          nitem[item.pagecode] = item.alias ? item.alias : item.pagecode
          nitem['keyVal'] = item.pageconfigurationid
          maps.push(nitem)
        })
        this.tableForm.passparameters = JSON.stringify(maps)
      }
    },
    clearTypeUpload (nload = []) {
      if (nload?.length) {
        const files = this.$refs['upload']
        files.map((item) => {
          item.imageUrl = ''
          item.$el.firstChild.value = ''
        })
      }
    },
    // 新增/编辑-确认
    submitClickHandler () {
      let flag = false
      const ndata = this.formItemArr.filter(item => item.datatype == 'password' || item.datatype == 'PASSWORD')
      const nload = this.formItemArr.filter(item => item.datatype == 'upload' || item.datatype == 'UPLOAD')
      const npass = this.tableForm.passparameters
      if (nload?.length) this.addTypeUpload(nload)
      if (ndata?.length) this.addTypePassWord(ndata)
      if (npass?.length) this.formatPass(npass)
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          flag = true
          this.clearTypeUpload(nload)
        } else {
          flag = false;
        }
      });
      return flag
    },
    isShow (isdisplay) {
      let show = false
      if (eval(isdisplay)) {
        show = true
      }
      else {
        show = false
      }
      return show
    }
  }
}
</script>
