<template>
  <ai-detail>
    <template slot="title">
      <ai-title title="数据源" isShowBack isShowBottomBorder @onBackClick="cancel">
      </ai-title>
    </template>
    <template slot="content">
      <ai-card title="数据源列表">
        <template #right>
          <el-button type="primary" @click="isShow = true">添加数据源</el-button>
        </template>
        <template #content>
          <ai-search-bar class="search-bar">
            <template slot="right">
              <el-input
                  v-model="search.name"
                  size="small"
                  v-throttle="() => {search.current = 1, getList()}"
                  placeholder="请输入名字"
                  clearable
                  @clear="search.current = 1, search.name = '', getList()"
                  suffix-icon="iconfont iconSearch">
              </el-input>
            </template>
          </ai-search-bar>
          <ai-table
              :tableData="tableData"
              :col-configs="colConfigs"
              :total="total"
              style="margin-top: 6px;"
              :border="true"
              :current.sync="search.current"
              :size.sync="search.size"
              @getList="getList">
            <el-table-column slot="options" width="160px" fixed="right" label="操作" align="center">
              <template slot-scope="{ row }">
                <div class="table-options">
                  <el-button type="text" @click="toEdit(row)">编辑</el-button>
                  <el-button type="text" @click="remove(row.id)">删除</el-button>
                </div>
              </template>
            </el-table-column>
          </ai-table>
        </template>
      </ai-card>
      <ai-dialog
          :visible.sync="isShow"
          width="920px"
          title="数据源"
          @close="onClose"
          @onConfirm="onConfirm">
        <el-form ref="form" :model="form" label-width="110px" label-position="right">
          <div class="ai-form">
            <el-form-item label="数据源描述" style="width: 100%;" prop="description" :rules="[{ required: true, message: '请输入数据源描述', trigger: 'blur' }]">
              <el-input
                  size="small"
                  placeholder="请输入数据源描述"
                  v-model="form.description">
              </el-input>
            </el-form-item>
            <el-form-item label="类型" style="width: 100%;" prop="dataRange" :rules="[{ required: true, message: '请选择数据范围', trigger: 'change' }]">
              <el-radio-group v-model="form.type">
                <el-radio label="0">村微应用</el-radio>
                <el-radio label="1">SQL</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="form.type === '1'" label="sql语句" style="width: 100%;" prop="description"
                          :rules="[{ required: true, message: '请输入sql语句', trigger: 'blur' }]">
              <el-input
                  :rows="8"
                  size="small"
                  type="textarea"
                  placeholder="请输入数据源描述"
                  v-model="form.sqlContent">
              </el-input>
            </el-form-item>
            <el-form-item v-if="form.type === '0'" label="村微应用" style="width: 100%;" prop="appId"
                          :rules="[{ required: true, message: '请选择村微应用', trigger: 'change' }]">
              <el-select size="small" style="width: 100%;" v-model="form.appId" placeholder="请选择村微应用" @change="onAppChange">
                <el-option
                    v-for="item in appList"
                    :key="item.id"
                    :label="item.appName"
                    :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="form.type === '0'" label="数据范围" style="width: 100%;" prop="dataRange"
                          :rules="[{ required: true, message: '请选择数据范围', trigger: 'change' }]">
              <el-radio-group v-model="form.dataRange">
                <el-radio label="0">全部</el-radio>
                <el-radio label="1">自定义条数</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="数据条数" style="width: 100%;" v-if="form.dataRange === '1' && form.type === '0'" prop="count"
                          :rules="[{ required: true, message: '请输入数据条数', trigger: 'blur' }]">
              <el-input
                  size="small"
                  placeholder="请输入数据条数"
                  v-model="form.count">
              </el-input>
            </el-form-item>
            <div v-if="form.type === '0'">
              <el-form-item :label="'统计项' + index" style="width: 100%;" v-for="(item, index) in form.statisticsConfigs" :key="'statisticsConfigs' + index">
                <div class="form-flex">
                  <div>
                    <el-select size="small" style="width: 160px;" v-model="item.fieldName" @change="e => onChooseField('statisticsConfigs', e, index)"
                               placeholder="请选择" clearable>
                      <el-option
                          v-for="(item, index) in filedList"
                          :key="index"
                          :label="item.fieldCnName"
                          :value="item.fieldName">
                      </el-option>
                    </el-select>
                    <el-select size="small" style="margin: 0 10px; width: 160px;" v-model="item.calcType" placeholder="请选择" clearable>
                      <el-option
                          v-for="item in dict.getDict('diyLargeScreenDatasourceCalcType2')"
                          :key="item.id"
                          :label="item.dictName"
                          :value="item.dictValue">
                      </el-option>
                    </el-select>
                    <el-input size="small" style="width: 165px;" placeholder="请输入别名" v-model="item.alias"></el-input>
                  </div>
                  <el-button type="danger" v-if="index > 0" @click="removeConfig('statisticsConfigs', index)">删除</el-button>
                </div>
              </el-form-item>
            </div>

            <el-form-item style="width: 100%;" v-if="form.type === '0'">
              <el-button type="primary" @click="add('statisticsConfigs')">添加统计项</el-button>
            </el-form-item>
            <div v-if="form.type === '0'">
              <el-form-item :label="'分组' + index" style="width: 100%;" v-for="(item, index) in form.groupConfigs" :key="'groupConfigs' + item.fieldName">
                <div class="form-flex">
                  <div>
                    <el-select size="small" style="width: 160px;" v-model="item.fieldName" placeholder="请选择" clearable>
                      <el-option
                          v-for="item in filedList"
                          :key="item.id"
                          :label="item.fieldCnName"
                          :value="item.fieldName">
                      </el-option>
                    </el-select>
                  </div>
                  <el-button type="danger" @click="removeConfig('groupConfigs', index)">删除</el-button>
                </div>
              </el-form-item>
            </div>
            <el-form-item style="width: 100%;" v-if="form.type === '0'">
              <el-button type="primary" @click="add('groupConfigs')">添加分组</el-button>
            </el-form-item>
            <div v-if="form.type === '0'">
              <el-form-item :label="'统计项' + index" style="width: 100%;" v-for="(item, index) in form.orderConfigs" :key="'orderConfigs' + item.fieldName">
                <div class="form-flex">
                  <div>
                    <el-select size="small" style="width: 160px;" v-model="item.fieldName" placeholder="请选择" clearable>
                      <el-option
                          v-for="item in filedList"
                          :key="item.id"
                          :label="item.fieldCnName"
                          :value="item.fieldName">
                      </el-option>
                    </el-select>
                    <el-select size="small" style="width: 160px; margin-left: 10px;" v-model="item.orderType" placeholder="请选择" clearable>
                      <el-option
                          v-for="item in orderTypeDict"
                          :key="item.id"
                          :label="item.label"
                          :value="item.value">
                      </el-option>
                    </el-select>
                  </div>
                  <el-button type="danger" @click="removeConfig('orderConfigs', index)">删除</el-button>
                </div>
              </el-form-item>
            </div>
            <el-form-item style="width: 100%;" v-if="form.type === '0'">
              <el-button type="primary" @click="add('orderConfigs')">添加排序</el-button>
            </el-form-item>
          </div>
        </el-form>
      </ai-dialog>
    </template>
  </ai-detail>
</template>

<script>
export default {
  name: 'SourceData',

  props: {
    instance: Function,
    dict: Object,
    params: Object,
    urlPrefix: String
  },

  data() {
    return {
      isShow: false,
      search: {
        current: 1,
        size: 10,
        name: ''
      },
      total: 0,
      colConfigs: [
        {prop: 'appName', label: '应用名'},
        {prop: 'appTableName', align: 'center', label: '表名'},
        {prop: 'description', align: 'center', label: '描述'},
        {prop: 'type', align: 'center', label: '类型', formart: v => v === '0' ? '村微应用' : 'sql语句'},
        {prop: 'createUserName', align: 'center', label: '创建人'},
        {prop: 'createTime', align: 'center', label: '创建时间'}
      ],
      tableData: [],
      filedList: [],
      appList: [],
      form: {
        orderType: 'asc',
        dataRange: '0',
        type: '0',
        sqlContent: '',
        appId: '',
        description: '',
        appName: '',
        appTableName: '',
        count: '100',
        statisticsConfigs: [{
          alias: '',
          calcType: '',
          dictCode: '',
          fieldCnName: '',
          fieldName: ''
        }],
        orderConfigs: [{
          alias: '',
          calcType: '',
          dictCode: '',
          fieldCnName: '',
          fieldName: ''
        }],
        groupConfigs: [{
          alias: '',
          calcType: '',
          dictCode: '',
          fieldCnName: '',
          fieldName: ''
        }]
      },
      id: '',
      orderTypeDict: [
        {
          value: 'asc',
          label: '升序'
        },
        {
          value: 'desc',
          label: '降序'
        }
      ]
    }
  },

  created() {
    this.dict.load(['diyLargeScreenDatasourceCalcType2']).then(() => {
      this.getList()
      this.getAppList()
    })
  },

  methods: {
    getInfo(id) {
      this.instance.post(`${this.urlPrefix}/wxcp/wxuser/queryDetailById?id=${id}`).then(res => {
        if (res.code === 0) {
          this.form = {
            ...res.data
          }
        }
      })
    },

    onChooseField(type, fieldName, index) {
      const dictCode = this.filedList.filter(v => v.fieldName === fieldName)[0].dictCode
      this.$set(this.form[type][index], 'dictCode', dictCode)
    },

    add(type) {
      this.form[type].push({
        alias: '',
        calcType: '',
        dictCode: '',
        fieldCnName: '',
        fieldName: ''
      })
    },

    removeConfig(type, index) {
      this.form[type].splice(index, 1)
    },

    toEdit(e) {
      this.id = e.id
      this.instance.post(`${this.urlPrefix}/appdiylargescreen/queryDatasourceDetailById?id=${e.id}`).then(res => {
        if (res.code === 0) {
          this.form = {
            ...res.data
          }

          this.form.dataRange = this.form.dataRange === '0' ? '0' : '1'
          this.form.count = res.data.dataRange
          this.filedList = this.appList.filter(v => v.id === res.data.appId).length && this.appList.filter(v => v.id === res.data.appId)[0].fields.map(item => {
            let value = []
            res.data.configs.forEach(v => {
              if (v.fieldName === item.fieldName) {
                value.push(v.calcType)
              }
            })

            return {
              ...item,
              value
            }
          })
          this.isShow = true
        }
      })
    },

    remove(id) {
      this.$confirm('确定删除该数据？').then(() => {
        this.instance.post(`${this.urlPrefix}/appquestionnairetemplate/delete?id=${id}`).then(res => {
          if (res.code == 0) {
            this.$message.success('删除成功！')
            this.getList()
          }
        })
      })
    },

    getList() {
      this.instance.post(`${this.urlPrefix}/appdiylargescreen/allDatasourceByPage`, null, {
        params: {
          ...this.search
        }
      }).then(res => {
        if (res.code == 0) {
          this.tableData = res.data.records
          this.total = res.data.total
        }
      })
    },

    getAppList() {
      this.instance.post(`${this.urlPrefix}/appdiylargescreen/allDatasourceApp`).then(res => {
        if (res.code === 0) {
          this.appList = res.data
        }
      })
    },

    onClose() {
      this.id = ''
      this.form.orderType = 'asc'
      this.form.dataRange = 0
      this.form.appId = ''
      this.form.description = ''
      this.form.appName = ''
      this.form.appTableName = ''
      this.form.count = 100
    },

    onAppChange(e) {
      const value = this.appList.filter(v => v.id === e)[0]
      this.form.appTableName = value.appTableName
      this.form.appName = value.appName
      this.form.statisticsConfigs = [{
        alias: '',
        calcType: '',
        dictCode: '',
        fieldCnName: '',
        fieldName: ''
      }]
      this.form.orderConfigs = [{
        alias: '',
        calcType: '',
        dictCode: '',
        fieldCnName: '',
        fieldName: ''
      }]
      this.form.groupConfigs = [{
        alias: '',
        calcType: '',
        dictCode: '',
        fieldCnName: '',
        fieldName: ''
      }]
      this.filedList = value.fields.map(v => {
        return {
          ...v,
          value: ''
        }
      })
    },

    onConfirm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let configs = []

          if (this.filedList.length) {
            this.filedList.forEach(item => {
              if (item.value.length) {
                item.value.forEach(v => {
                  configs.push({
                    alias: item.fieldCnName,
                    calcType: v,
                    fieldCnName: item.fieldCnName,
                    fieldName: item.fieldName,
                    dictCode: item.dictCode,
                    orderType: this.orderType
                  })
                })
              }
            })
          }

          this.instance.post(`${this.urlPrefix}/appdiylargescreen/addOrUpdateDatasource`, {
            ...this.form,
            configs,
            id: this.id ? this.id : '',
            dataRange: this.form.dataRange === '0' ? 0 : this.form.count
          }).then(res => {
            if (res.code === 0) {
              this.$message.success(this.id ? '编辑成功' : '添加成功')
              this.search.current = 1
              this.isShow = false

              this.getList()
            }
          })
        }
      })
    },

    cancel() {
      this.$router.push({})
    }
  }
}
</script>

<style scoped lang="scss">
.form-flex {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
