<template>
  <a-card :bordered="false" class="card-area">
    <ItemFactor @handleSearch="handleSearch" @reset="reset"></ItemFactor>
    <div>
      <div class="operator" style="width: auto">
        <a-dropdown v-hasPermission="['healthKnowledge:export']">
          <a-menu slot="overlay" v-if="showMoreStatus">
              <a-menu-item key="export-data" @click="exportExcel">导出数据</a-menu-item>
          </a-menu>
          <a-button>
              更多操作 <a-icon type="down" />
          </a-button>
        </a-dropdown>
        <a-button v-hasPermission="['healthKnowledge:batchDelete']" @click="batchDelete">删除</a-button>
        <a-button type="primary" @click="showAdd" v-hasPermission="['healthKnowledge:add']">新增信息</a-button>
        <ImportExcel
          v-hasPermission="['healthKnowledge:importData']" ref="ImportExcel"
          :importUrl="importUrl"
          :acceptFile="acceptFile"
          @importSuccess="handleImportSuccess"
          @importError="handleImportError"/>
      </div>
      <!-- 表格区域 -->
      <a-table
        ref="TableInfo"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="pagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange"
        :scroll="{ x: 1000 }"
        size="small">
        <template slot="remark" slot-scope="text, record">
          <a-popover placement="topLeft">
            <template slot="content">
              <div style="max-width: 200px">{{text}}</div>
            </template>
            <p style="width: 200px;margin-bottom: 0">{{text}}</p>
          </a-popover>
        </template>
        <template slot="operation" slot-scope="text, record">
          <a-button type="primary" size="small"  @click="showEdit(record)" v-hasPermission="['healthKnowledge:edit']">
            编辑
          </a-button>
          <a-button type="primary" size="small" @click="viewParticulars(record)">
            查看详情
          </a-button>
        </template>
        <template slot="authUserRender" slot-scope="text, record">
          <a-tag color="#2db7f5">{{handleTypeByValue(record.authUserId,authUserIdOption)}}</a-tag>
        </template>
        <template slot="publisherRender" slot-scope="text, record">
          <a-tag color="#2db7f5">{{handleTypeByValue(record.publisherId,authUserIdOption)}}</a-tag>
        </template>
        <!--数据列动态选择渲染-->
        <template slot="filterDropdown" slot-scope="text, record">
          <a-row style="margin-left: 20px" type="flex" justify="space-between">
            <a-checkbox @change="onColumnCheckAllChange">
                全选
            </a-checkbox>
          </a-row>
          <a-checkbox-group @change="onColumnPlainChange" :defaultValue="columnShowList">
            <a-row type="flex" justify="space-between">
              <a-col style="margin-left: 20px" v-for="(item,index) in dataColumns" :key="item.index"
                :span="4"
                :order="item.index" >
                <a-checkbox :value="item.dataIndex" :disabled="item.disabled">
                  {{item.title}}
                </a-checkbox>
              </a-col>
            </a-row>
          </a-checkbox-group>
        </template>
        <!--图片查看的模版-->
        <template slot="imageTags" slot-scope="text, record">
          <img :src="record.surfaceImage" @click="handleTagImgChange(record.surfaceImage)" style="width: 30px;height: 30px" />
        </template>
      </a-table>
    </div>
    <a-modal :visible="previewImageVisible" :footer="null" @cancel="handleImagePreviewCancel">
      <img alt="example" style="width: 100%" :src="previewImageUrl" />
    </a-modal>
    <!--数据详情-->
    <ItemParticulars
      ref="ItemParticulars">
    </ItemParticulars>
    <ItemEdit
      ref="ItemEdit"
      @close="handleEditClose"
      @success="handleEditSuccess">
    </ItemEdit>
    <!-- 信息新增-->
    <ItemAdd
      ref="ItemAdd"
      @close="handleItemAddClose"
      @success="handleItemAddSuccess">
    </ItemAdd>
  </a-card>
</template>
<script>
import ImportExcel from '@/components/import/ImportExcel'
import ItemEdit from './ItemEdit'
import ItemAdd from './ItemAdd'
import ItemFactor from './ItemFactor'
import ItemParticulars from './ItemParticulars'
import moment from 'moment'
import baseUtils from '@/utils/baseUtils'
import {mapState, mapMutations} from 'vuex'
moment.locale('zh-cn')

export default {
  name: 'ItemList',
  components: {
    ImportExcel:ImportExcel,
    ItemAdd:ItemAdd,
    ItemEdit:ItemEdit,
    ItemFactor:ItemFactor,
    ItemParticulars:ItemParticulars,
    baseUtils:baseUtils,
  },
  data () {
    return {
      authUserIdOption:[],
      showMoreStatus:false,
      pageUrl:'api/v1/healthKnowledge/queryByPage',//分页查询链接
      exportUrl:'api/v1/healthKnowledge/exportData', //导出链接
      acceptFile:'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      importUrl:process.env.BASE_API+'api/v1/healthKnowledge/importData', //文件时上传,
      itemData:{ //行信息
        data:{

        },
      },
      loading: false,
      validateStatus:'',//校验状态
      help:'',//提示信息
      previewImageVisible: false, //预览图片的弹出框
      previewImageUrl: '', //预览图片的URL
      advanced: false,
      dataSource: [],
      //选中的列
      columnShowList:[],
      //最终要显示的列
      columns:[],
      dataColumns:[
        {
          title: '序号',
          dataIndex: 'id',
          width: 100,
          fixed: 'left',
          align:'center',
          showStatus:true,
          disabled:true,
          scopedSlots: {
            filterDropdown: 'filterDropdown',
          },
        },
        {
          title: '健康知识主题',
          dataIndex: 'itemSubject',
          showStatus:true,
          disabled:false,
        },
        {
          title: '发布者',
          dataIndex: 'publisherId',
          showStatus:true,
          disabled:false,
          scopedSlots: { customRender: 'publisherRender' },
        },
        {
          title: '操作',
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' },
          align:'center',
          fixed: 'right',
          width: 150,
          showStatus:true,
          disabled:true,
        }
      ],
      selectedRowKeys: [],
      paginationInfo: null,
      pagination: {
        pageSizeOptions: ['10', '20', '30', '40', '100'],
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
      },
      expressForm: this.$form.createForm(this),
      queryParams: {
        itemContent:'',
        itemSubject:'',
        publisherId:'',
      },
    }
  },
  created () {
    //this.setOtherData()
  },
  computed: {
    ...mapState({
        currentUser: state => state.account.user
    }),
  },
  mounted () {
    this.fetch()
  },
  methods: {
    //设置需要显示的列
    setColumns(){
      let data = this.dataColumns
      //console.log("this.dataColumns : "+JSON.stringify(this.dataColumns));
      if(data.length > 0){
        this.columns.splice(0,this.columns.length)
        this.columnShowList.splice(0,this.columnShowList.length)
        data.map(item => {
          let showStatus  = item.showStatus
          let dataIndex = item.dataIndex
          if(showStatus === true){
            this.columns.push(item)
            this.columnShowList.push(dataIndex)
          }
        })
      }
    },
    onColumnCheckAllChange(e){
      let checked = e.target.checked
      let data = this.dataColumns
      console.log('e.target.checked  : '+e.target.checked )
      if(checked){
        if(data.length > 0){
          this.columns.splice(0,this.columns.length)
          this.columnShowList.splice(0,this.columnShowList.length)
          data.map(item => {
            let dataIndex  = item.dataIndex
            this.columns.push(item)
            this.columnShowList.push(dataIndex)
          })
        }
      }else{
        this.setColumns();
      }
    },
    onColumnPlainChange(checkedValues) {
      let data = checkedValues
      if(data && data.length > 0) {
        //console.log('选中的列 ', JSON.stringify(data));
        this.dataColumns.map(item => {
          let dataIndex = String(item.dataIndex)
          //console.log('需要被查找的数据数据:dataIndex: '+dataIndex)
          //console.log('需要被查找的数据数据:data.indexOf(dataIndex): '+data.indexOf(dataIndex))
          if(dataIndex && data.indexOf(dataIndex) > -1){
            //console.log('查找到需要定位的数据:dataIndex: '+dataIndex)
            item.showStatus = true
          }else{
            item.showStatus = false
          }
        })
        this.setColumns();
      }
    },
    handleSearch(queryParams){
      if(!baseUtils.isNull(queryParams)){
        this.queryParams =  queryParams
      }
      this.fetch({
        ...this.queryParams
      })
    },
    handleImportSuccess(){ //处理导入成功
      console.log('导入成功')
      this.fetch(...this.queryParams)
    },
    handleImportError(){
      this.$message.error('导入失败')
    },
    async setOtherData(){
      this.setColumns(); //设置数据列
      this.authUserIdOption = await this.$commonConstants.authUserIdOption()
    },
    handleTypeByValue(value,optionList){
      console.log('optionList : '+JSON.stringify(optionList))
      console.log('value : '+value)
      if(baseUtils.isNull(value)){
        return '无'
      }
      if(!optionList || !optionList.length >0){
        return '';
      }
      let resultList  =
        optionList.filter(item => item.value == value);
      console.log(JSON.stringify(resultList))
      if(resultList && resultList.length > 0){
        return resultList[0].text;
      }else{
        return '无'
      }
    },
    handleItemAddClose(){
      console.log('handleItemAddClose')
    },
    handleItemAddSuccess(){
      console.log('handleItemAddSuccess')
      this.$message.success('新增成功')
      this.search()
    },
    showAdd(){ //新增数据
      this.$refs.ItemAdd.showAdd({})
    },
    handleEditSuccess () {
      this.$message.success('更新成功')
      this.search()
    },
    handleEditClose () {
      this.search()
    },
    moment,
    //查看数据信息
    viewParticulars (record) {
      this.$refs.ItemParticulars.showParticulars(record)
    },
    handleParticularsClose(){

    },
    handleTagImgChange(url){
      this.previewImageVisible = true
      this.previewImageUrl = url
    },
    handleImagePreviewCancel(){
      this.previewImageVisible = false
      this.previewImageUrl = ''
    },
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
      if (!this.advanced) {
          this.queryParams.fieldName = ''
      }
    },
    //设置数据内容
    showEdit (record) {
      this.$refs.ItemEdit.showEdit(record)
    },
    //批量删除
    batchDelete () {
      if (!this.selectedRowKeys.length) {
        this.$message.warning('请选择需要删除的记录')
        return
      }
      let that = this
      this.$confirm({
        title: '确定删除所选中的记录?',
        content: '当您点击确定按钮后，这些记录将会被彻底删除',
        centered: true,
        onOk () {
          let mainIdList = []
          for (let key of that.selectedRowKeys) {
            mainIdList.push(that.dataSource[key].healthKnowledgeId)
          }
            that.$postBodyRequest('api/v1/healthKnowledge/batchDeleteItem/',{
              mainIdList:mainIdList
            }).then(() => {
            that.$message.success('删除成功')
            that.selectedRowKeys = []
            that.search()
          })
        },
        onCancel () {
          that.selectedRowKeys = []
        }
      })
    },
    exportExcel () {
      this.$exportData(this.exportUrl, {
        ...this.queryParams
      })
    },
    search () {
      this.fetch({
        ...this.queryParams
      })
    },
    reset () {
      // 取消选中
      this.selectedRowKeys = []
      // 重置分页
      this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent
      if (this.paginationInfo) {
        this.paginationInfo.current = this.pagination.defaultCurrent
        this.paginationInfo.pageSize = this.pagination.defaultPageSize
      }
      this.paginationInfo = null
      // 重置查询参数
      this.queryParams = {}
      this.fetch()
    },
    handleTableChange (pagination, filters, sorter) {
      this.paginationInfo = pagination
      this.fetch({
          ...this.queryParams
      })
    },
    fetch (params = {}) {
      this.loading = true
      if (this.paginationInfo) {
        // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
        this.$refs.TableInfo.pagination.current = this.paginationInfo.current
        this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize
        params.pageSize = this.paginationInfo.pageSize
        params.pageNum = this.paginationInfo.current
      } else {
        // 如果分页信息为空，则设置为默认值
        params.pageSize = this.pagination.defaultPageSize
        params.pageNum = this.pagination.defaultCurrent
      }
      this.$postBodyRequest(this.pageUrl, {
          ...params
      }).then((r) => {
        let data = r.data.data
        const pagination = { ...this.pagination }
        pagination.total = baseUtils.isNull(data.total) ? 0 : data.total
        this.loading = false
        this.dataSource = data.rows
        this.pagination = pagination
        this.setOtherData();
      })
    }
  }
}
</script>

<style lang="less" scoped>
    /*webpack 会以~符号作为前缀的路径视为依赖模块去解析*/
    @import "~@static/less/Common";
</style>
