<template>
  <!-- <div @click="goPath">模型视图</div> -->
  <div id="modelView">
    <div class="top-header">
      <div class="title">选择模型</div>
      <img @click="changeView" src="../../assets/images/modelView/changeView.png" alt="">
    </div>
    <template v-if="showCard">
      <div class="card-view">
        <div
          class="card-item"
          @click="goPath(item)"
          v-for="(item, index) in cardData"
          :key="index">
          <div class="top">
            <div class="name">{{ item.modelName }}</div>
            <img src="../../assets/images/modelView/top.png" alt="" @click.stop="toTop(item.id)">
          </div>
          <div class="bottom">
            <div class="info">
              <div>{{ item.modelCode }}</div>
              <div>{{ item.modelDesc }}</div>
            </div>
            <img :src="imgList[index%3].url" alt="">
          </div>
        </div>
      </div>
      <a-pagination
        show-quick-jumper
        :default-current="1"
        show-size-changer
        :total="total"
        :page-size="paramsCard.pageSize"
        @showSizeChange="onShowSizeChange"
        @change="onChange"
        :hideOnSinglePage="true"
        :page-size-options="pageSizeOptions"/>
    </template>
    <template v-else>
      <div id="manger-wrap">
        <div class="left-tree">
          <h2>主数据分类</h2>
          <div class="title">
            <a-input-search
              placeholder="请输入类别名称/代码"
              style="width: 200px"
              @change="onSearch" />
            <div class="action">
              <div @click="onExpandOpenAll">全部展开</div>
              <!-- <div @click="onExpandClose">全部收起</div> -->
            </div>
          </div>
          <a-tree
            v-if="treeData.length>0"
            :replaceFields="{
              title:'catalogName',
              key: 'catalogCode',
              children:'children',
              value:'catalogCode'
            }"
            show-line
            :defaultExpandAll="true"
            :expandedKeys="expandedKeys"
            tree-default-expand-all
            :tree-data="treeData"
            @expand="onExpand"
            @select="onClassSelect">
            <template slot="catalogName" slot-scope="{ catalogName }">
              <span v-if="catalogName.indexOf(searchValue) > -1">
                {{ catalogName.substr(0, catalogName.indexOf(searchValue)) }}
                <span style="color: #f50">{{ searchValue }}</span>
                {{ catalogName.substr(catalogName.indexOf(searchValue) + searchValue.length) }}
              </span>
              <span v-else>{{ catalogName }}</span>
            </template>
            <a-icon slot="switcherIcon" type="down" />
          </a-tree>
        </div>
        <div class="right-table">
          <div class="table-content">
            <FilterTable
              ref="table"
              :columns="columns"
              :dataSource="dataSource"
              :total="total"
              :isSelected="false"
            />
          </div>
        </div>
      </div>
    </template>
  </div>
</template>

<script type="text/ecmascript-6">
import { getClassTreeApi } from '@/api/model/kindManger'
import { getModelListApi } from '@/api/model/modelManger'

import { getList, modelTop } from '@/api/model/attribute'
import FilterTable from '@/components/filterTable'
const getParentKey = (key, tree) => {
  let parentKey
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i]
    if (node.children) {
      if (node.children.some(item => item.catalogCode === key)) {
        parentKey = node.catalogCode
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children)
      }
    }
  }
  return parentKey
}
const dataList = []
const generateList = data => {
  for (let i = 0; i < data.length; i++) {
    const node = data[i]
    const catalogCode = node.catalogCode
    const catalogName = node.catalogName
    dataList.push({ catalogCode, catalogName: catalogName })
    if (node.children) {
      generateList(node.children)
    }
  }
}
	// var path = ''
	export default {
		beforeRouteEnter(to, from, next) {
			// path = to.query.redirectPath
			next()
		},
		components: {
			FilterTable
		},
		data() {
			return {
				imgList: [
					{ url: require('../../assets/images/modelView/model1.png') },
					{ url: require('../../assets/images/modelView/model2.png') },
					{ url: require('../../assets/images/modelView/model3.png') }
				],
				showCard: true,
				cardData: [],
				totalCard: 0,
				total: 0,
				treeData: [],
				expandedKeys: ['0'],
				paramsCard: {
          pageSize: 16,
          pageNum: 1
        },
				params: {
          pageSize: 10,
          pageNum: 1
        },
				pageSizeOptions: ['8', '16'],
				dataSource: [],
				columns: [
					{
            title: '序号',
            dataIndex: 'orderNum',
            key: 'sort',
            width: 60,
            align: 'center',
            scopedSlots: { customRender: 'sort' },
            customRender: (text, record, index) => {
							return (<span>{++index}</span>)
						}
          },
					{
            title: '模型名称',
            dataIndex: 'modelName',
            key: 'modelName',
            align: 'center',
						customRender: (text, record, index) => {
							return (<span class="view">{text}</span>)
						},
						customCell: this.clickRow
          },
					{
            title: '模型代码',
            dataIndex: 'modelCode',
            key: 'modelCode',
            align: 'center',
            scopedSlots: { customRender: 'sort' }
          },
					{
            title: '所属分类',
            dataIndex: 'catalogName',
            key: 'catalogName',
            align: 'center',
            scopedSlots: { customRender: 'sort' }
          },
					{
            title: '创建人',
            dataIndex: 'createBy',
            key: 'createBy',
            align: 'center',
            scopedSlots: { customRender: 'sort' }
          },
					{
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            align: 'center',
            scopedSlots: { customRender: 'sort' }
          }
				]
			}
		},
		mounted() {
			this.getList()
			this.getClassTree()
      this.getTableList(0)
		},
		methods: {
			addAttr(data) {
        data.map((item) => {
          item.scopedSlots = { title: 'catalogName' }
          if (item.children) this.addAttr(item.children)
        })
        return data
      },
			getList() {
				getList(this.paramsCard).then((res) => {
					if (res.code === 200) {
						this.cardData = res.rows
						this.total = res.total
					}
				})
			},
			getTableList(catalogId) {
        getModelListApi({ catalogId, ...this.params }).then((res) => {
          if (res.code === 200) {
            this.dataSource = res.rows
          }
        })
      },
			changeView() {
				this.showCard = !this.showCard
			},
			clickRow(record) {
				return {
					on: {
						click: () => {
							this.goPath(record)
						}
					}
				}
			},
			goPath(item) {
        if (this.$route.query.redirectPath !== '/standard/attribute') {
        const { id, modelName, modelCode, tableStatus } = item
				if (!(+tableStatus)) {
					this.$router.push({
						path: this.$route.query.redirectPath,
						query: {
							id,
							modelName,
							modelCode
						}
					})
				} else {
					this.$message.info('模型数据表未创建')
				}
        } else {
          const { id, modelName, modelCode } = item
          this.$router.push({
						path: this.$route.query.redirectPath,
						query: {
							id,
							modelName,
							modelCode
						}
					})
        }
			},
			onChange(pageNum) {
        this.$set(this.paramsCard, 'pageNum', pageNum)
        getList(this.paramsCard).then((res) => {
					if (res.code === 200) {
						this.cardData = res.rows
						this.total = res.total
					}
				})
			},
			getClassTree() {
        getClassTreeApi().then((res) => {
          if (res.code === 200) {
            this.treeData = this.addAttr(res.data.rows)
            generateList(this.treeData)
          }
        })
      },
			onSearch(e) {
        const value = e.target.value
        const expandedKeys = dataList
        .map(item => {
          if (item.catalogName.indexOf(value) > -1) {
            return getParentKey(item.catalogCode, this.treeData)
          }
          return null
        })
        .filter((item, i, self) => item && self.indexOf(item) === i)
        Object.assign(this, {
          expandedKeys,
          searchValue: value,
          autoExpandParent: true
        })
      },
      onExpandClose() {
        this.expandedKeys = []
      },
      onExpandOpenAll() {
        this.expandedKeys = []
      },
			onClassSelect(selectedKeys, info) {
        selectedKeys[0] && this.getTableList(selectedKeys[0])
        info.node.onExpand()
        console.log('selected', selectedKeys, info)
      },
      onExpand(selectedKeys) {
        this.expandedKeys = selectedKeys
        console.log('Trigger Expand', selectedKeys, this.expandedKeys)
      },
			toTop(id) {
				modelTop({ id }).then((res) => {
					if (res.code === 200) {
						this.$message.info('置顶成功')
						this.getList()
					} else {
						this.$message.error('置顶失败')
					}
				})
			},
			onShowSizeChange(current, pageSize) {
				this.$set(this.paramsCard, 'pageSize', pageSize)
			}
		},
    watch: {
      path: {
      handler(val) {
        console.log('1', 1)
        this.path = this.$route.path
      }
    }
  }
	}
</script>

<style lang="less" scoped>
@import url('../model/_style/index.less');
#modelView{
	padding:0 16px;
	.top-header{
		width: 100%;
		// height: 48px;
		padding: 10px 12px;
		background-color: #ffffff;
		box-shadow: 0px 1px 15px 0px
			#ebf0f7;
		border-radius: 3px;
		display: flex;
		justify-content: space-between;
		align-items: center;
		position: relative;
		&::before{
			content: '';
			width: 4px;
			height: 26px;
			background-color: #3b75f5;
			position: absolute;
			left: 0;
			top: 50%;
			transform: translateY(-50%);
		}
		>img{
			width: 26px;
			height: 26px;
			display: block;
		}
	}
	.card-view{
		margin-top: 20px;
		width: 100%;
		display: grid;
		grid-template-columns: repeat(4,1fr);
		// grid-template-rows: repeat(4,146px);
		grid-gap: 34px;
		.card-item{
			height: 146px;
			background: #fff;
			border-radius: 10px;
			box-shadow: 0px 5px rgba(0,0,0,.1);
			padding: 12px 12px 0 16px;
			.top{
				display: flex;
				justify-content: space-between;
				.name{
					font-family: MicrosoftYaHei-Bold;
					font-size: 16px;
					font-weight: normal;
					font-stretch: normal;
					letter-spacing: 0px;
					color: #333333;
				}
				>img{
					width: 12px;
					height: 16px;
					cursor: pointer;
				}
			}
			.bottom{
				margin-top: 8px;
				display: flex;
				justify-content: space-between;
				align-items: flex-end;
				.info{
					font-family: MicrosoftYaHei;
					font-size: 14px;
					font-weight: normal;
					font-stretch: normal;
					line-height: 24px;
					letter-spacing: 0px;
					color: #333333;
					opacity: 0.7;
					>div{
						margin-top: 10px;
					}
				}
			}
		}
	}
}
.ant-pagination{
	width: 100%;
	padding: 20px 0;
	text-align: center;
}
.view{
	color: #427ffd;
	cursor: pointer;
}
</style>
