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

    <div class="filter-container">
      <el-form :inline="true" size="mini" v-model="inquireInfo">
        <el-form-item
          v-for="condition in inquireInfo.conditionList"
          :key="condition.id"
          :label="condition.conditionName"
          v-show="condition.visible">
          <el-input
            style="width: 150px;"
            v-if="condition.dataType === 0"
            :disabled="condition.disabled"
            v-model="condition.conditionValue">
          </el-input>
          <el-date-picker
            v-else-if="condition.dataType === 1"
            :disabled="condition.disabled"
            v-model="condition.conditionValue"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy - MM - dd "
            value-format="yyyy-MM-dd"
            :default-time="['00:00:00', '23:59:59']"
            :picker-options="datePickerOptions">
          </el-date-picker>
          <el-select
            style="width: 150px;"
            v-else-if="condition.dataType === 2"
            v-model="condition.conditionValue"
            :disabled="condition.disabled">
            <el-option
              v-for="item in dicDataOptionsMap[condition.id]"
              :key="condition.id + '_' + item.id"
              :label="item.dictLabel"
              :value="item.dictValue">
            </el-option>
          </el-select>
          <template v-else-if="condition.dataType === 3">
            <!--真正值-->
            <el-input
              v-model="condition.conditionValue"
              v-show="false"
            >
            </el-input>
            <!--显示值-->
            <el-input
              clearable
              disabled
              style="width: 200px;"
              v-model="condition.conditionDisplay"
              @click.native="createInnerVisible = true;innerType = condition.selectDicType;innerConditionId=condition.id">
              <el-button slot="append" class="el-icon-circle-close"
                         @click.stop="clearConditionSelect(condition.id)">
              </el-button>
              <el-button
                slot="append"
                @click="createInnerVisible = true;innerType = condition.selectDicType;innerConditionId=condition.id">选择
              </el-button>
            </el-input>
          </template>
        </el-form-item>
      </el-form>

      <el-button size="mini" class="filter-item" type="primary" icon="el-icon-search" @click="searchData">
        搜索
      </el-button>

      <el-button
        size="mini"
        v-show="inquireInfo.canExport === 1"
        class="filter-item"
        type="success"
        icon="el-icon-document"
        @click="exportData">
        导出
      </el-button>

      <el-button size="mini" class="filter-item" type="warning" icon="el-icon-refresh-left" @click="initCondition">
        清除条件
      </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="getData"/>
        </el-tooltip>
      </div>

      <el-table
        size="mini"
        :data="tableData"
        v-loading="listLoading"
        ref="inquireTable"
        border
        :summary-method="getStatistics"
        :show-summary="tableSummary"
        style="margin-top: 10px">
        <!--                <template v-for="column in columnNames">-->
        <!--                  <el-table-column-->
        <!--                    v-if="column.linkUrl"-->
        <!--                    :key="column.id"-->
        <!--                    :prop="column.columnField"-->
        <!--                    :label="column.columnName"-->
        <!--                    :width="column.columnWidth"-->
        <!--                    v-show="column.visible"-->
        <!--                    show-overflow-tooltip>-->
        <!--                    <template slot-scope="{row}">-->
        <!--                      <el-button @click.stop="redirectToUrl(column.linkUrl, row)" type="text" size="small">{{-->
        <!--                          row[column.columnField]-->
        <!--                        }}-->
        <!--                      </el-button>-->
        <!--                    </template>-->
        <!--                  </el-table-column>-->

        <!--                  <el-table-column-->
        <!--                    v-else-->
        <!--                    :key="column.id"-->
        <!--                    :prop="column.columnField"-->
        <!--                    :label="column.columnName"-->
        <!--                    :width="column.columnWidth"-->
        <!--                    v-show="column.visible"-->
        <!--                    show-overflow-tooltip>-->
        <!--                  </el-table-column>-->

        <!--                </template>-->
        <el-table-column width="1"></el-table-column>
        <re-table-column :child-columns="columnNames"></re-table-column>
      </el-table>
      <pagination
        v-show="(listData.total>0) && (inquireInfo.queryInPage === 1)"
        :total="listData.total"
        :page.sync="listData.page"
        :limit.sync="listData.pageSize"
        @pagination="getData"/>
      <div class="totalCount" v-show="inquireInfo.queryInPage === 0">共 {{ tableData.length }} 条</div>

      <el-dialog title="选择档案" :append-to-body="true" :visible.sync="createInnerVisible">
        <!--产品档案-->
        <productInfo
          v-if="innerType === 'productInfo'"
          :key="timer"
          :is-choose="true"
          :sourceType="1"
          @chooseRow='chooseDoc'></productInfo>
        <!--客户档案-->
        <clientInfo
          v-if="innerType === 'clientInfo'"
          :key="timer"
          :is-choose="true"
          :sourceType="1"
          @chooseRow='chooseDoc'></clientInfo>
        <!--纸张档案-->
        <paperInfo
          v-if="innerType === 'paperInfo'"
          :key="timer"
          :is-choose="true"
          :sourceType="1"
          @chooseRow='chooseDoc'></paperInfo>
        <!--辅料档案-->
        <accessoriesInfo
          v-if="innerType === 'accessoriesInfo'"
          :key="timer"
          :is-choose="true"
          :sourceType="1"
          @chooseRow='chooseDoc'></accessoriesInfo>
        <!--部门档案-->
        <departmentInfo
          v-if="innerType === 'departmentInfo'"
          :key="timer"
          :is-choose="true"
          :sourceType="1"
          @chooseRow='chooseDoc'></departmentInfo>
        <!--担保人档案-->
        <guarantorInfo
          v-if="innerType === 'guarantorInfo'"
          :key="timer"
          :is-choose="true"
          :sourceType="1"
          @chooseRow='chooseDoc'></guarantorInfo>
        <!--机台档案-->
        <machineInfo
          v-if="innerType === 'machineInfo'"
          :key="timer"
          :is-choose="true"
          :sourceType="1"
          @chooseRow='chooseDoc'></machineInfo>
        <!--科目档案-->
        <subjectInfo
          v-if="innerType === 'subjectInfo'"
          :key="timer"
          :is-choose="true"
          :sourceType="1"
          @chooseRow='chooseDoc'></subjectInfo>
        <!--供应商档案-->
        <supplierInfo
          v-if="innerType === 'supplierInfo'"
          :key="timer"
          :is-choose="true"
          :sourceType="1"
          @chooseRow='chooseDoc'></supplierInfo>
        <!--人员档案-->
        <userInfo
          v-if="innerType === 'userInfo'"
          :key="timer"
          :is-choose="true"
          :sourceType="1"
          @chooseRow='chooseDoc'></userInfo>
        <!--班组档案-->
        <workTeamInfo
          v-if="innerType === 'workTeamInfo'"
          :key="timer"
          :is-choose="true"
          :sourceType="1"
          @chooseRow='chooseDoc'></workTeamInfo>
      </el-dialog>
    </div>

  </div>
</template>

<script>
import {execInquireResult, getDicDataList, getInquireInfo} from '@/api/doc/inquire/inquire'
import productInfo from '@/views/productFile/product/productInfo'
import clientInfo from '@/views/doc/client/clientList'
import paperInfo from '@/views/baseInfo/paper/paperInfo'
import accessoriesInfo from '@/views/baseInfo/accessories/accessoriesInfo'
import departmentInfo from '@/views/system/department/department'
import guarantorInfo from '@/views/baseInfo/guarantor'
import machineInfo from '@/views/baseInfo/machineInfo'
import subjectInfo from '@/views/baseInfo/subjectInfo'
import supplierInfo from '@/views/baseInfo/supplier/supplierInfo'
import userInfo from '@/views/system/user/user'
import workTeamInfo from '@/views/baseInfo/workTeam/workTeam'

export default {
  name: 'ExecInquireResult',
  components: {
    reTableColumn: () => import('@/components/recursionTableColumn/recursionTableColumn'),
    productInfo, clientInfo, paperInfo, accessoriesInfo, departmentInfo, guarantorInfo,
    machineInfo, subjectInfo, supplierInfo, userInfo, workTeamInfo
  },
  data() {
    return {
      inquireInfo: {
        canExport: 0,
        queryInPage: 0,
        conditionList: [],
        resultColumnList: []
      },

      datePickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },

      dicDataOptionsMap: {},

      createInnerVisible: false,
      innerType: '',
      innerConditionId: 0,

      columnNames: [],
      tableSummary: false,


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

      listLoading: false,
      tableData: [],
      collection: {},

      tabTitle: '',
      initDoSearch: 0,
      transParams: '',
      tempRoute: null
    }
  },
  mounted() {
    this.initData()

    this.tempRoute = Object.assign({}, this.$route)
    if (this.tabTitle != '')
      this.setTagsViewTitle()
  },

  methods: {
    // 设置标签名称
    setTagsViewTitle() {
      const title = this.tabTitle

      // console.log("tempRoute2",this.tempRoute);
      const route = Object.assign({}, this.tempRoute, {title: `${title}`})
      // console.log("route",route)
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    // 获取查询统计结构
    initData() {
      const _that = this
      const queryParams = this.$route.path.split('/').slice(-1)[0]
      if (!queryParams) {
        _that.$message.error('未传入有效的查询参数')
        return
      }

      // 允许查询统计列转跳至其他查询统计,传入参数格式为
      // 查询统计id.转跳标题.1转跳后自动查询0不查询.转跳查询初始参数

      const paramArr = queryParams.split('.')
      let queryId = 0
      for (let i = 0; i < paramArr.length; i++) {
        if (i === 0) {
          // 查询统计id
          queryId = paramArr[i]
        } else if (i === 1) {
          // 转跳标题
          _that.tabTitle = paramArr[i]
          // urldecode
          _that.tabTitle = decodeURI(_that.tabTitle)
        } else if (i === 2) {
          // 1转跳后自动查询0不查询
          _that.initDoSearch = paramArr[i]
        } else if (i === 3) {
          // 转跳查询初始参数
          _that.transParams = paramArr[i]
        }
      }

      const data = {
        id: queryId
      }
      // console.log(data);
      getInquireInfo(data).then(response => {
        _that.inquireInfo = response.data
        _that.initView()
      }).catch(err => {
        _that.$message.error(err)
      })
    },

    // 根据查询统计结构初始化界面
    initView() {
      const _that = this
      // 如果是转跳来的,将条件值填入,并将对应的条件置灰
      const transParamArr = new Map()
      if (_that.transParams !== '') {
        _that.transParams.split('&').forEach(x => {
          transParamArr.set(x.split('=')[0], x.split('=')[1])
        })
      }
      _that.inquireInfo.conditionList.forEach(x => {
        // 默认值给上
        x.conditionValue = x.defaultValue
        // 默认都启用
        x.disabled = false

        if (x.dataType === 2) {
          // 选择字典,需要动态填值
          const dicParam = {dictTypeText: x.selectDicType}
          getDicDataList(dicParam).then(response => {
            // console.log(response)
            // _that.dicDataOptionsMap.set(x.id, response.data)
            this.$set(this.dicDataOptionsMap, x.id, response.data)
          }).catch(err => {
            _that.$message.error(err)
          })
        }
        if (x.dataType === 1 && x.visible != 0) {
          x.conditionValue = [];
          let yy = new Date().getFullYear();
          let mm = (new Date().getMonth() + 1)< 10 ? '0' + (new Date().getMonth()+1) : (new Date().getMonth()+1);
          let dd = new Date().getDate()<10 ? '0'+new Date().getDate() : new Date().getDate();
          var data1 =  yy + '-' + mm + '-' + '01';
          var data2 =   yy + '-' + mm + '-' + dd;
          x.conditionValue.push(data1)
          x.conditionValue.push(data2)
        }

        // 如果是转跳来的,将条件值填入,并将对应的条件置灰
        const value = transParamArr.get(x.conditionField)
        if (value !== undefined) {
          // urldecode
          x.conditionValue = decodeURI(value)
          x.disabled = true
        }
      })

      this.inquireInfo.conditionList.sort((x, y) => x.sortAsc - y.sortAsc)
      // this.inquireInfo.resultColumnList.sort((x, y) => x.sortAsc - y.sortAsc)
      this.sortColumnAsc(this.inquireInfo.resultColumnList)
      this.columnNames = Object.assign([], this.inquireInfo.resultColumnList)
      this.tableSummary = (this.columnNames.findIndex(x => x.hasStatistics === 1) >= 0)

      // 要不要初始化查询
      if (this.initDoSearch == 1) {
        this.searchData()
      }
    },

    sortColumnAsc(columnList) {
      const _that = this
      columnList.sort((x, y) => x.sortAsc - y.sortAsc)
      columnList.forEach(x => {
        if (x.childColumnList) {
          _that.sortColumnAsc(x.childColumnList)
        }
      })
    },

    // 查询结果
    getData() {
      const _that = this
      _that.listLoading = true
      const page = {
        pageIndex: _that.listData.page,
        pageSize: _that.listData.pageSize
      }
      const conditionList = []
      _that.inquireInfo.conditionList.forEach(x => {
        const condition = {
          conditionField: x.conditionField,
          conditionValue: x.conditionValue
        }
        conditionList.push(condition)
      })

      console.log("121212",conditionList);


      const data = {
        'idInquire': _that.inquireInfo.id,
        'conditionList': JSON.stringify(conditionList),
        'exportFlag': 0,
        'page': JSON.stringify(page)
      }
      // console.log(data);
      execInquireResult(data).then(response => {
        console.log(response)
        // //  组合表单数据
        _that.tableData = response.data
        _that.listData.total = response.total
        _that.collection = response.collection
        // console.log(_that.tableData)
        _that.listLoading = false
      }).catch(err => {
        _that.$message.error(err)
        _that.listLoading = false
      })
    },
    // 如果有统计项,计算统计项
    getStatistics(param) {
      const _that = this
      const {columns, data} = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        const resultColumn = _that.columnNames.find(x => x.columnField === column.property)
        if (resultColumn) {
          if (resultColumn.hasStatistics === 1) {
            sums[index] = _that.collection[resultColumn.columnField]
          } else {
            sums[index] = ''
          }
        }
      })
      return sums
    },

    tableRefresh() {
      this.getData()
    },

    searchData() {
      this.listData.page = 1
      this.getData()
    },

    initCondition() {
      this.inquireInfo.conditionList.forEach(x => {
        // 默认值给上
        x.conditionValue = x.defaultValue
        // 默认都启用
        x.disabled = false

        if (x.dataType === 3) {
          x.conditionDisplay = ''
        }
      })
    },

    exportData() {
      const _that = this
      const conditionList = []
      _that.inquireInfo.conditionList.forEach(x => {
        const condition = {
          conditionField: x.conditionField,
          conditionValue: x.conditionValue
        }
        conditionList.push(condition)
      })

      const data = {
        'idInquire': _that.inquireInfo.id,
        'conditionList': JSON.stringify(conditionList),
        'exportFlag': 1
      }
      // console.log(data);
      execInquireResult(data).then(response => {
        console.log(response)
        if (response.httpCode === 200) {
          _that.$message.success('导出任务提交成功,请到我的任务查看导出结果')
        } else _that.$message.error(response.msg)
      }).catch(err => {
        _that.$message.error(err)
      })
    },

    redirectToUrl(template, row) {
      const destUrl = getParamsFromTemplate(template, row)
      this.$router.push(destUrl)
      // console.log(destUrl);
    },

    chooseDoc(data) {
      this.createInnerVisible = false
      // console.log(data);
      const condition = this.inquireInfo.conditionList.find(x => x.id === this.innerConditionId)
      condition.conditionValue = data.id
      condition.conditionDisplay = data.name
    },

    clearConditionSelect(idCondition) {
      const condition = this.inquireInfo.conditionList.find(x => x.id === idCondition)
      condition.conditionValue = condition.defaultValue
      condition.conditionDisplay = ''
    }
  }
}
</script>

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

.totalCount {
  margin-right: 10px;
  margin-top: 10px;
  font-weight: 400;
  color: #606266;
  font-size: 13px;
}

::v-deep .el-dialog__body {
  padding-top: 10px;
}

.board-column {
  min-width: 100px;
  min-height: 100px;
  height: auto;
  overflow: hidden;
  background: #f0f0f0;
  border-radius: 3px;

  .board-column-header {
    height: 50px;
    line-height: 50px;
    overflow: hidden;
    padding: 0 20px;
    text-align: center;
    background: #333;
    color: #fff;
    border-radius: 3px 3px 0 0;
  }

  .board-column-content {
    height: auto;
    overflow: hidden;
    border: 10px solid transparent;
    min-height: 60px;
    display: flex;
    justify-content: flex-start;
    flex-direction: column;
    align-items: center;

    .board-item {
      cursor: pointer;
      width: 100%;
      height: 64px;
      margin: 5px 0;
      background-color: #fff;
      text-align: left;
      line-height: 54px;
      padding: 5px 10px;
      box-sizing: border-box;
      box-shadow: 0px 1px 3px 0 rgba(0, 0, 0, 0.2);
    }
  }
}
</style>
