<template>
  <div class="app-container">
    <div class="filter-container">

      <el-input v-model="search.keyWord" placeholder="关键字" style="width: 200px;" class="filter-item"/>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="searchData">
        搜索
      </el-button>

      <el-button
        v-if="webType && isChoose == false"
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-plus"
        @click="handleCreateAdd">
        增加查询统计
      </el-button>
      <el-button
        v-if="webType && isChoose == false"
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-upload"
        @click="handleImportAdd">
        导入查询统计
      </el-button>
      <div class="top-right-btn">
        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button size="mini" circle icon="el-icon-refresh" @click="getList"/>
        </el-tooltip>
      </div>
    </div>
    <el-table
      :data="tableData"
      v-loading="listLoading"
      style="width: 100%;margin-bottom: 20px;"
      row-key="id"
      :size="!webType ? 'mini':''"
      border
      default-expand-all>
      <el-table-column
        prop="id"
        label="id"
        width="80">
      </el-table-column>
      <el-table-column
        prop="inquireName"
        label="报表名称">
      </el-table-column>
      <el-table-column
        prop="inquireFuncName"
        label="脚本名称">
        <template slot-scope="{row}">
          <el-link
            type="primary"
            @click="$router.push({path:'/baseInfo/scriptCode',query:{businessCode:row.inquireFuncName,codeId:row.id}})">
            {{ row.inquireFuncName }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column align="center" label="状态" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag v-if="row.voidFlag==0" type="success">
            启用
          </el-tag>
          <el-tag v-else-if="row.voidFlag==1" type="danger">
            禁用
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="left" align="center" width="280" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <template v-if="webType">
            <template v-if="!isChoose">
              <el-button @click="handleUpdate(row)" type="primary" size="mini">
                编辑
              </el-button>
              <el-button @click="editStatus(row.id,'1')" type="danger" v-if="row.voidFlag==0" size="mini">
                禁用
              </el-button>
              <el-button @click="editStatus(row.id,'0')" v-else-if="row.voidFlag==1" size="mini">
                启用
              </el-button>
              <el-button @click="exportConfig(row.id)" size="mini">
                导出配置
              </el-button>

            </template>
            <template v-else>
              <el-button @click="chooseThis(row)" type="primary" size="mini">
                选择
              </el-button>
            </template>
          </template>
          <template v-else>
            <el-button @click="ERPChoose(row)" type="primary" size="mini">
              选择
            </el-button>
          </template>
        </template>
      </el-table-column>

    </el-table>
    <pagination v-show="listData.total>0" :total="listData.total" :page.sync="listData.page"
                :limit.sync="listData.pageSize" @pagination="getList"/>

    <el-dialog :title="dialogTitle" :close-on-click-modal="false" :visible.sync="dialogVisible" width="80%">
      <el-form label-width="130px" size="mini" label-position="right">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="查询统计名称">
              <el-input v-model="form.inquireName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="查询统计类型">
              <el-select v-model="form.inquireType">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="导出">
              <el-select v-model="form.canExport">
                <el-option
                  label="允许"
                  :value="1"></el-option>
                <el-option
                  label="不允许"
                  :value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否分页">
              <el-select v-model="form.queryInPage">
                <el-option
                  label="是"
                  :value="1"></el-option>
                <el-option
                  label="否"
                  :value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-tabs v-model="activeName" @tab-click="handleClick">
              <el-tab-pane label="报表列定义" name="first">
                <el-button @click="addResultColumn" type="green" size="mini" style="margin-bottom: 10px">增加
                </el-button>
                <el-button @click="addExcelTemp" type="danger" size="mini" style="margin-bottom: 10px">生成导出模板
                </el-button>
                <el-table
                  :data="form.resultColumnList"
                  style="width: 100%;margin-bottom: 20px;"
                  row-key="id"
                  size="mini"
                  border
                  default-expand-all
                  :tree-props="{children: 'childColumnList'}">
                  <el-table-column label="列显示名">
                    <template slot-scope="{row}">
                      <span v-if="row.status == 0">{{ row.columnName }}</span>
                      <el-input v-else-if="row.status == 1" size="mini" v-model="row.columnName"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="列字段名">
                    <template slot-scope="{row}">
                      <span v-if="row.status == 0">{{ row.columnField }}</span>
                      <el-input v-else-if="row.status == 1" size="mini" v-model="row.columnField"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="转跳地址">
                    <template slot-scope="{row}">
                      <span v-if="row.status == 0">{{ row.linkUrl }}</span>
                      <el-input v-else-if="row.status == 1" size="mini" v-model="row.linkUrl"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="列宽">
                    <template slot-scope="{row}">
                      <span v-if="row.status == 0">{{ row.columnWidth }}</span>
                      <el-input v-else-if="row.status == 1" size="mini" v-model="row.columnWidth"></el-input>
                    </template>
                  </el-table-column>

                  <el-table-column label="是否可见">
                    <template slot-scope="{row}">
                      <template v-if="row.status == 0">
                        <span v-if="row.visible == 1">是</span>
                        <span v-else-if="row.visible == 0">否</span>
                      </template>
                      <el-select v-else-if="row.status == 1" size="mini" v-model="row.visible">
                        <el-option label="是" :value="1"></el-option>
                        <el-option label="否" :value="0"></el-option>
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column label="是否需要统计">
                    <template slot-scope="{row}">
                      <template v-if="row.status == 0">
                        <span v-if="row.hasStatistics == 1">是</span>
                        <span v-else-if="row.hasStatistics == 0">否</span>
                      </template>
                      <el-select v-else-if="row.status == 1" size="mini" v-model="row.hasStatistics">
                        <el-option label="是" :value="1"></el-option>
                        <el-option label="否" :value="0"></el-option>
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column label="统计格式">
                    <template slot-scope="scope">
                      <span v-if="scope.row.status == 0">{{ scope.row.statisticsFormat }}</span>
                      <el-input v-else-if="scope.row.status == 1" size="mini"
                                v-model="scope.row.statisticsFormat"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="排序">
                    <template slot-scope="scope">
                      <span v-if="scope.row.status == 0">{{ scope.row.sortAsc }}</span>
                      <el-input v-else-if="scope.row.status == 1" size="mini" min='1' type="number"
                                v-model="scope.row.sortAsc"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="210" align="center" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                      <el-button v-if="!scope.row.status" @click="scope.row.status = 1" type="primary" size="mini">
                        编辑
                      </el-button>
                      <el-button v-else @click="scope.row.status = 0" type="success" size="mini">
                        保存
                      </el-button>
                      <el-button @click="addResultColumnChild(scope)" type="green" size="mini"
                                 style="margin-bottom: 10px">增加
                      </el-button>
                      <el-button @click="deleteRow(scope,1)" type="danger" size="mini">
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-tab-pane>
              <el-tab-pane label="报表条件定义" name="second">
                <el-button @click="addCondition" type="green" size="mini" style="margin-bottom: 10px">增加</el-button>
                <el-table
                  :data="form.conditionList"
                  style="width: 100%;margin-bottom: 20px;"
                  row-key="id"
                  size="mini"
                  border
                  default-expand-all>
                  <el-table-column label="条件名称">
                    <template slot-scope="{row}">
                      <span v-if="row.status == 0">{{ row.conditionName }}</span>
                      <el-input v-else-if="row.status == 1" size="mini" v-model="row.conditionName"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="条件字段">
                    <template slot-scope="{row}">
                      <span v-if="row.status == 0">{{ row.conditionField }}</span>
                      <el-input v-else-if="row.status == 1" size="mini" v-model="row.conditionField"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="数据类型">
                    <template slot-scope="{row}">
                      <template v-if="row.status == 0">
                        <span v-if="row.dataType == 0">输入</span>
                        <span v-else-if="row.dataType == 1">日期</span>
                        <span v-else-if="row.dataType == 2">选择</span>
                        <span v-else-if="row.dataType == 3">档案</span>
                      </template>
                      <el-select v-else-if="row.status == 1" size="mini" v-model="row.dataType">
                        <el-option label="输入" :value="0"></el-option>
                        <el-option label="日期" :value="1"></el-option>
                        <el-option label="选择" :value="2"></el-option>
                        <el-option label="档案" :value="3"></el-option>
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column label="dicType">
                    <template slot-scope="{row}">
                      <span v-if="row.status == 0">{{ row.selectDicType }}</span>
                      <template v-else-if="row.status == 1 ">
                        <el-select v-if="row.dataType == 2" size="mini" v-model="row.selectDicType">
                          <el-option
                            v-for="item in dictData"
                            :key="item.id"
                            :label="item.dictName"
                            :value="item.dictType"></el-option>
                        </el-select>
                        <el-input v-else-if="row.dataType == 3" size="mini" v-model="row.selectDicType"></el-input>
                      </template>
                    </template>
                  </el-table-column>
                  <el-table-column label="条件默认值">
                    <template slot-scope="{row}">
                      <span v-if="row.status == 0">{{ row.defaultValue }}</span>
                      <el-input v-else-if="row.status == 1" size="mini" v-model="row.defaultValue"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="是否可见">
                    <template slot-scope="{row}">
                      <template v-if="row.status == 0">
                        <span v-if="row.visible == 1">是</span>
                        <span v-else-if="row.visible == 0">否</span>
                      </template>
                      <el-select v-else-if="row.status == 1" size="mini" v-model="row.visible">
                        <el-option label="是" :value="1"></el-option>
                        <el-option label="否" :value="0"></el-option>
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column label="排序">
                    <template slot-scope="scope">
                      <span v-if="scope.row.status == 0">{{ scope.row.sortAsc }}</span>
                      <el-input v-else-if="scope.row.status == 1" min='1' type="number" size="mini"
                                v-model="scope.row.sortAsc"></el-input>
                    </template>
                  </el-table-column>

                  <el-table-column label="操作" width="135" align="center" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                      <el-button v-if="!scope.row.status" @click="editRow(scope,2)" type="primary" size="mini">
                        编辑
                      </el-button>
                      <el-button v-else @click="saveRow(scope,2)" type="success" size="mini">
                        保存
                      </el-button>
                      <el-button @click="deleteRow(scope,2)" type="danger" size="mini">
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-tab-pane>
            </el-tabs>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogStatus==='1'?addBtn():editBtn()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="导出配置" :close-on-click-modal="false" :visible.sync="exportDialogVisible" width="50%">
      <el-input
        type="textarea"
        autosize
        placeholder="请输入内容"
        v-model="exportJson">
      </el-input>
    </el-dialog>
    <el-dialog title="导入配置" :close-on-click-modal="false" :visible.sync="importDialogVisible" width="50%">
      <el-input
        type="textarea"
        autosize
        placeholder="请输入内容"
        v-model="importJson">
      </el-input>
      <el-button @click="doImportJson()" type="primary" size="mini">
        导入
      </el-button>
    </el-dialog>
    <cancledialog @tableRefresh="tableRefresh" ref="confirmDialog"></cancledialog>
  </div>
</template>

<script>
import {
  addInquireInfo,
  getInquireMainInfo,
  queryInquireMainInfo,
  selectDictTypeList,
  updateInquireInfo,
  addExcelTemplate
} from '@/api/baseInfo/inquireMainInfo/inquireMainInfo'
import Cancledialog from '@/components/Dialog/Cancledialog.vue'

const form = {
  inquireName: '', // 查询统计名称,
  inquireType: '', // 查询统计类型 0:groovy脚本/1:sql语句,
  canExport: 1, // 允许导出
  queryInPage: 1, //默认分页
  resultColumnList: [], // 报表列,
  conditionList: [] // 查询条件,
}
const resultColumn = {
  columnName: '',
  columnField: '',
  columnWidth: '',
  visible: 1,
  hasStatistics: '',
  statisticsFormat: '',
  sortAsc: '',
  linkUrl: '',
  status: 1,
  childColumnList: [],
  idParentColumn: 0
}
const condition = {
  conditionName: '',
  conditionField: '',
  dataType: '',
  defaultValue: '',
  visible: 1,
  selectDicType: '',
  sortAsc: '',
  status: 1
}
export default {
  name: 'InquireMainInfo',
  components: {
    Cancledialog
  },
  props: {
    isChoose: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      webType: true,
      paperInfoVisible: false,
      dialogStatus: 1, // 1增加，2修改
      dialogTitle: '',
      dialogVisible: false,
      exportDialogVisible: false,
      exportJson: '',
      importDialogVisible: false,
      importJson: '',
      search: {
        keyWord: ''
      },
      form: Object.assign({}, form),
      options: [
        {
          label: 'groovy脚本',
          value: 0
        },
        {
          label: 'sql语句',
          value: 1
        }
      ],
      activeName: 'first',

      listData: {
        total: 0,
        page: 1,
        pageSize: 10
      },

      confirmdialog: false,
      listLoading: false,
      tableData: [],
      dictData: [], // 字典
      tempId: -1
    }
  },
  mounted() {
    this.getList()
    this.getDictType()
    if (this.$route.query.type === undefined) {
      this.webType = true
    } else {
      this.webType = false
    }
  },
  methods: {
    // 获取列表
    getList() {
      const _that = this
      _that.listLoading = true
      var params = _that.search
      var page = {
        pageIndex: _that.listData.page,
        pageSize: _that.listData.pageSize
      }
      var data = {
        'params': JSON.stringify(params),
        'page': JSON.stringify(page)
      }
      // console.log(data);
      queryInquireMainInfo(data).then(response => {
        console.log(response)
        const data = response.data
        // //  组合表单数据
        _that.tableData = data
        _that.listData.total = response.total
        // console.log(_that.tableData)
        _that.listLoading = false
      }).catch(err => {
        _that.$message.error(err)
        _that.listLoading = false
      })
    },
    // 获取字典
    getDictType() {
      const _that = this
      var data = {}
      selectDictTypeList(data).then(response => {
        console.log(response)
        _that.dictData = response.data
      }).catch(err => {
        _that.$message.error(err)
      })
    },

    // 增加查询统计
    handleCreateAdd() {
      const _that = this
      _that.form = Object.assign({}, form)
      _that.activeName = 'first'
      _that.form.resultColumnList = []
      _that.form.conditionList = []
      _that.dialogTitle = '增加查询统计'
      _that.dialogStatus = '1'
      _that.dialogVisible = true
    },
    //导入查询统计
    handleImportAdd() {
      const _that = this
      _that.importJson = ''
      _that.importDialogVisible = true
    },
    doImportJson() {
      const _that = this
      if (_that.importJson == '') {
        _that.$message.error('请粘贴导出的json')
      }

      var inquireInfo = _that.importJson
      // var data = {
      //   'inquireInfo': inquireInfo
      // }
      // console.log(data);
      // return

      addInquireInfo(inquireInfo).then(res => {
        // console.log(res);
        if (res.httpCode == 200) {
          _that.dialogVisible = false
          _that.$message({
            message: '增加成功',
            type: 'success'
          })
          _that.tableRefresh()
          _that.importDialogVisible = false
        } else {
          _that.$message.error(res.msg)
        }
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    // 刷新变革
    tableRefresh() {
      // 刷新变革
      this.getList()
    },
    // 切换标签
    handleClick(tab, event) {
      // console.log(tab, event)
    },
    // 增加报表列
    addResultColumn() {
      var _that = this
      _that.form.resultColumnList.map(item => {
        if (item.status) {
          item.status = 0
        }
        return item
      })
      var item = JSON.parse(JSON.stringify(resultColumn))
      item.sortAsc = _that.form.resultColumnList.length + 1
      _that.form.resultColumnList.push(item)
    },
    // 生成excel模板
    addExcelTemp() {
      const _that = this
      const data = {
        'id': _that.form.id
      }
      addExcelTemplate(data).then(response => {
        if (response.httpCode === 200) {
          _that.$message.success('生成模板成功')
        } else {
          _that.$message.error(response.msg)
        }
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    // 增加子集
    addResultColumnChild(scope) {
      console.log(scope)
      const _that = this
      _that.form.resultColumnList.map(item => {
        if (item.status) {
          item.status = 0
        }
        return item
      })

      var item = JSON.parse(JSON.stringify(resultColumn))
      _that.tempId--
      item.id = _that.tempId
      // _that.form.resultColumnList[scope.$index].child.push(item)
      scope.row.childColumnList.push(item)
    },
    // 增加行
    addCondition() {
      var _that = this
      _that.form.conditionList.map(item => {
        if (item.status) {
          item.status = 0
        }
        return item
      })
      var item = Object.assign({}, condition)
      item.sortAsc = _that.form.conditionList.length + 1
      _that.form.conditionList.push(item)
    },
    /**
     * 编辑行
     * type 1为报表列，2为查询条件
     */
    editRow(scope, type) {
      var _that = this
      var array
      if (type == 1) {
        array = _that.form.resultColumnList
      } else {
        array = _that.form.conditionList
      }
      array.forEach((item, index) => {
        if (scope.$index == index) {
          item.status = 1
        }
      })
    },
    /**
     * 保存行
     * type 1为报表列，2为查询条件
     */
    saveRow(scope, type) {
      var _that = this
      var array
      if (type == 1) {
        array = _that.form.resultColumnList
      } else {
        array = _that.form.conditionList
      }
      array.forEach((item, index) => {
        if (scope.$index == index) {
          item.status = 0
        }
        if (type == 2) {
          if (!(scope.row.dataType === 2 || scope.row.dataType === 3)) {
            scope.row.selectDicType = ''
          }
        }
      })
    },
    /**
     * 删除行
     * type 1为报表列，2为查询条件
     */
    deleteRow(scope, type) {
      var _that = this
      var array
      if (type == 1) {
        array = _that.form.resultColumnList
      } else {
        array = _that.form.conditionList
      }
      // array.splice(scope.$index, 1)
      _that.shellArr(array, scope.row.id)
    },
    shellArr(array, id, parentArr = [], index = 0) {
      const _that = this
      if (array.constructor != Array) {
        if (array.id == id) {
          parentArr.splice(index, 1)
          return
        }
        for (let j = 0; j < array.childColumnList.length; j++) {
          console.log(array.childColumnList[j].columnName)
          _that.shellArr(array.childColumnList[j], id, array.childColumnList, j)
        }
      } else {
        for (let i = 0; i < array.length; i++) {
          var item = array[i]
          console.log('item', item)
          if (item.id == id) {
            array.splice(i, 1)
            return
          }
          if (item.childColumnList) {
            for (let j = 0; j < item.childColumnList.length; j++) {
              _that.shellArr(item.childColumnList[j], id, item.childColumnList, j)
            }
          }
        }
      }
    },
    // 增加纸张档案
    addBtn() {
      const _that = this
      var inquireInfo = JSON.stringify(_that.form)
      // var data = {
      //   'inquireInfo': inquireInfo
      // }
      // console.log(data);
      // return

      addInquireInfo(inquireInfo).then(res => {
        // console.log(res);
        if (res.httpCode == 200) {
          _that.dialogVisible = false
          _that.$message({
            message: '增加成功',
            type: 'success'
          })
          _that.tableRefresh()
        } else {
          _that.$message.error(res.msg)
        }
      }).catch(err => {
        _that.$message.error(err)
        _that.dialogVisible = true
      })
    },

    // 唤起修改
    handleUpdate(row) {
      const _that = this
      _that.form = Object.assign({}, form)
      _that.dialogTitle = '修改查询统计档案'
      _that.dialogVisible = true
      _that.dialogStatus = '2'

      var idPrint = row.id
      var data = {
        id: idPrint
      }

      getInquireMainInfo(data).then(res => {
        console.log(res)
        const data = res.data

        _that.form = {
          id: data.id,
          inquireName: data.inquireName, // 查询统计名称,
          inquireType: data.inquireType, // 查询统计类型 0:groovy脚本/1:sql语句,
          canExport: data.canExport,
          queryInPage: data.queryInPage
          // resultColumnList: data.resultColumnList, // 报表列,
          // conditionList: data.conditionList // 查询条件,
        }
        // (data.resultColumnList).forEach((item) => {
        //   item.status = 0
        // })
        _that.setState(data.resultColumnList)
        _that.form.resultColumnList = data.resultColumnList;
        (data.conditionList).forEach((item) => {
          item.status = 0
        })
        _that.form.conditionList = data.conditionList
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    // 设置status值
    setState(list) {
      const _that = this
      list.forEach(item => {
        item.status = 0
        if (item.childColumnList.length > 0) {
          _that.setState(item.childColumnList)
        }
      })
    },
    // 修改
    editBtn() {
      const _that = this
      var inquireInfo = JSON.stringify(_that.form)
      // var data = {
      //   'inquireInfo': inquireInfo
      // }

      updateInquireInfo(inquireInfo).then(res => {
        // console.log(res);
        if (res.httpCode == 200) {
          _that.dialogVisible = false
          _that.$message({
            message: '修改成功',
            type: 'success'
          })
          _that.tableRefresh()
        } else {
          _that.$message.error(res.msg)
        }
      }).catch(err => {
        _that.$message.error(err)
        _that.dialogVisible = true
      })
    },

    // 启用禁用
    editStatus(id, status) {
      var _that = this
      var inquireInfo = {
        id: id,
        voidFlag: status
      }
      var params = {
        'inquireInfo': JSON.stringify(inquireInfo)
      }

      var url = '/doc/voidInquireInfo'
      _that.$refs.confirmDialog.updataClick(params, url)
    },

    // 获取当前查询统计的配置json,用以在其他网站导入
    exportConfig(id) {
      const _that = this
      let idPrint = id
      let data = {
        id: idPrint
      }

      getInquireMainInfo(data).then(res => {
        console.log(res)
        _that.exportJson = JSON.stringify(res.data)
        _that.exportDialogVisible = true
      }).catch(err => {
        _that.$message.error(err)
      })
    },

    // 搜索
    searchData() {
      this.listData.page = 1
      this.getList()
    }
  }
}
</script>

<style lang="scss" scoped>
.filter-container {
  margin-bottom: 15px;
}
</style>
