<template>
  <ai-list v-if="pageShow">
    <template slot="title">
      <ai-title :title="configs.applicationName" isShowBottomBorder></ai-title>
    </template>
    <template slot="content">
      <ai-search-bar v-if="searchList.length">
        <template #left>
          <div v-for="(item, index) in searchList" :key="index">
            <ai-select
              v-model="search[item.searchValue]"
              :placeholder="'请选择'+item.label" clearable
              @change="$forceUpdate();(page.current = 1), getList()"
                       :selectList="dict.getDict(item.dict)"
                       v-if="item.type == 'dict'">
            </ai-select>
            <ai-search v-else-if="item.type == 'date'" :label="item.label">
              <el-date-picker size="small" v-model="search[item.searchValue]" type="daterange" range-separator="至"
                              start-placeholder="开始日期" end-placeholder="结束日期"
                              @change="$forceUpdate();(page.current = 1), getList()"
                              value-format="yyyy-MM-dd"/>
            </ai-search>
            <ai-search v-else-if="item.type == 'time'" :label="item.label">
              <el-time-picker is-range size="small" v-model="search[item.searchValue]" range-separator="至"
                              start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围"
                              @change="$forceUpdate();(page.current = 1), getList()"
                              value-format="HH:mm:ss"></el-time-picker>
            </ai-search>
            <ai-search v-else-if="item.type == 'area'" :label="item.label">
              <ai-area-get :instance="instance" v-model="search[item.searchValue]"/>
            </ai-search>
          </div>
        </template>
        <template #right v-if="showRightInput">
          <el-input :placeholder="placeholder" v-model="search.searchParam" size="small"
                    @change="$forceUpdate();(page.current = 1), getList()" clearable prefix-icon="iconfont iconSearch"/>
        </template>
      </ai-search-bar>
      <ai-search-bar>
        <template #left>
          <el-button type="primary" icon="iconfont iconAdd" size="small"
                     v-if="configs.insertEnable == 1" @click="toAdd('', 'Add')">添加
          </el-button>
          <el-button icon="iconfont iconDelete" size="small" :disabled="ids.length == 0"
                     v-if="configs.batchDelEnable == 1" @click="delAll()">删除
          </el-button>
        </template>
        <template #right>
          <ai-import :instance="instance" v-if="configs.importEnable == 1" type="appapplicationinfo"
                     :importParams="{appId}" :tplParams="{appId}" :name="configs.applicationName" @success="getList()">
            <el-button icon="iconfont iconImport">导入</el-button>
          </ai-import>
          <el-button icon="iconfont iconExported" size="small" v-if="configs.exportEnalbe == 1" @click="down()"
                    >导出
          </el-button>
        </template>
      </ai-search-bar>
      <ai-table class="ai-table" :tableData="tableData" :col-configs="colConfigs" :total="page.total"
                :current.sync="page.current" :size.sync="page.size" @getList="getList" :dict="dict"
                @selection-change="(v) => (ids = v.map((e) => e.id))">
        <el-table-column v-for="(item, indexs) in colConfigs" :key="indexs" :slot="item.slot" :label="item.label"
                         show-overflow-tooltip
                         align="center">
          <template slot-scope="{ row }">
            <div v-if="item.type != 'checkbox' && item.dict">
              {{ $dict.getLabel(item.dict, row[item.fieldDbName]) || '-' }}
            </div>
            <div v-if="item.type == 'rtf'" v-html="row[item.fieldDbName]"></div>
            <div v-if="item.type == 'checkbox'">{{ row[item.fieldDbName] }}</div>
          </template>
        </el-table-column>
        <el-table-column slot="options" label="操作" align="center" width="200">
          <template slot-scope="{ row }">
            <div class="table-options">
              <el-button type="text" @click="toDetail(row, 'Detail')">详情</el-button>
              <el-button type="text" @click="toDetail(row, 'Add')" v-if="configs.editEnable == 1">编辑</el-button>
              <el-button type="text" @click="del(row.id)" v-if="configs.deleteEnable == 1">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </ai-table>
    </template>
  </ai-list>
</template>

<script>
export default {
  name: 'List',
  props: {
    instance: Function,
    dict: Object,
    params: Object,
    appId: String,
    configs: Object
  },
  data() {
    return {
      pageShow: false,
      tableData: [],
      colConfigs: [],
      page: {
        size: 10,
        current: 1,
        total: 0,
      },
      search: {
        searchParam: '',
      },
      searchList: [],
      ids: [],
      showRightInput: false,
      placeholder: '请输入',
    }
  },
  created() {
    this.initConfigs()
  },
  methods: {
    initConfigs() {
      var dictList = []
      var colList = []
      var searchList = []
      var placeholderList = []
      this.configs.showListFields.map((item) => {
        var colItem
        if (item.dictionaryCode) {
          dictList.push(item.dictionaryCode)
          colItem = {
            slot: item.fieldDbName,
            label: item.fieldName,
            dict: item.dictionaryCode,
            fieldDbName: item.fieldDbName,
            type: item.type
          }
        } else if (item.type == 'rtf') {
          colItem = {label: item.fieldName, type: item.type, slot: item.fieldDbName, fieldDbName: item.fieldDbName}
        } else if (item.type == 'area') {
          colItem = {prop: item.fieldDbName + '_name', label: item.fieldName, align: "center"}
        } else {
          colItem = {prop: item.fieldDbName, label: item.fieldName, align: "center"}
        }
        colList.push(colItem)
      })
      this.configs.fuzzyQueryFields.map((item) => {
        var searchItem = {}
        if (item.dictionaryCode) {
          searchItem = {
            type: 'dict',
            label: item.fieldName,
            dict: item.dictionaryCode,
            searchValue: item.fieldDbName
          }
        }

        if (item.type == 'input' || item.type == 'name' || item.type == 'idNumber' || item.type == 'phone') {
          placeholderList.push(item.fieldName)
          this.showRightInput = true
        }

        if (item.type == 'date') {
          searchItem = {
            type: 'date',
            label: item.fieldName,
            searchValue: item.fieldDbName
          }
        }

        if (item.type == 'time') {
          searchItem = {
            type: 'time',
            label: item.fieldName,
            searchValue: item.fieldDbName
          }
        }

        if (item.type == 'area') {
          searchItem = {
            type: 'area',
            label: item.fieldName,
            searchValue: item.fieldDbName
          }
        }

        this.$set(this.search, item.fieldDbName, '')
        searchList.push(searchItem)
      })

      this.colConfigs = colList
      this.searchList = searchList
      this.$forceUpdate()

      var text = placeholderList.join('/')
      this.placeholder = this.placeholder + text

      if (this.configs.batchDelEnable == 1) {
        this.colConfigs.unshift({type: 'selection', width: 100})
      }
      if (dictList.length) {
        this.getDictList(dictList)
      } else {
        this.pageShow = true
        this.getList()
      }
    },
    getDictList(listName) {
      this.dict.load(listName.join(',')).then(() => {
        this.pageShow = true
        this.getList()
      })
    },
    getList() {
      this.instance.post(`/app/appapplicationinfo/list?appId=${this.appId}&current=${this.page.current}&size=${this.page.size}`, {...this.search}).then((res) => {
        if (res?.data) {
          this.tableData = res.data.records
          this.page.total = res.data.total
        }
      })
    },
    toDetail(item, type) {
      this.$emit('change', {
        type: type,
        params: item,
        backType: 'List'
      })
    },
    toAdd() {
      this.$emit('change', {
        type: 'Add',
        params: {
          type: 'Add',
        }
      })
    },
    del(id) {
      this.$confirm("删除后不可恢复，是否要删除？", {
        type: 'error'
      }).then(() => {
        this.instance.post(`/app/appapplicationinfo/delete?appId=${this.appId}&ids=${id}`).then((res) => {
          if (res.code == 0) {
            this.$message.success("删除成功！");
            this.getList();
          }
        })
      });
    },
    delAll() {
      if (this.ids.length > 100) {
        return this.$message.error("删除的数据最多不能超过100条！");
      }
      var id = this.ids.join(',')
      this.del(id)
    },

    reset() {
      Object.keys(this.search).forEach((e) => {
        this.search[e] = ''
      })
      this.getList()
    },
    down() {
      var id = ''
      if (this.ids.length) {
        id = this.ids.join(',')
      }
      this.instance.post(`/app/appapplicationinfo/export?appId=${this.appId}&ids=${id}`, this.search, {
        responseType: 'blob',
        timeout: 100000
      }).then(res => {
        if (res?.type == "application/json") {
          let reader = new FileReader()
          reader.readAsText(res, "utf-8")
          reader.onload = e => {
            if (e.target.readyState === 2) {
              let ret = JSON.parse(e.target.result)
              if (ret?.code == 0) {
                this.$message.success(ret.msg)
              } else this.$message.error(ret.msg)
            }
          }
        } else {
          const link = document.createElement('a')
          let blob = new Blob([res], {type: res.type})
          link.style.display = 'none'
          link.href = URL.createObjectURL(blob)
          link.setAttribute('download', this.configs.applicationName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        }
      }).catch((err) => {
        this.$error.success(err)
      })
    }
  },
}
</script>

<style scoped lang="scss">
.mar-b10 {
  margin-bottom: 10px;
}
</style>
