<template>
  <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="onExpandCloseAll">全部收起</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"
        :auto-expand-parent="autoExpandParent"
        :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">
      <h2>表单建模</h2>
      <!-- <div class="button-wrap">
        <a-button type="add" @click="addForm">新增模型</a-button>
        <a-button type="view" @click="editForm" :disabled="$refs.table&&$refs.table.selectedRows.length!==1">编辑</a-button>
        <a-button type="delete" :disabled="$refs.table&&$refs.table.selectedRows.length!==1">
          <a-popconfirm
            title="确定删除选中的模型吗?"
            ok-text="是"
            cancel-text="否"
            @confirm="deleteForm('删除模型')"
          >
            <a href="#">删除</a>
          </a-popconfirm>
        </a-button>
        <a-dropdown-button @click="handleButtonClick" :disabled="$refs.table&&$refs.table.selectedRows.length!==1">
          数据表操作
          <a-menu slot="overlay" @click="createTable">
            <a-menu-item key="1"> <a-icon type="folder-add" />创建数据表</a-menu-item>
            <a-menu-item key="2">
              <span>
                <a-icon type="delete" />
                <a-popconfirm
                  title="确定删除选中的数据表吗?"
                  ok-text="是"
                  cancel-text="否"
                  @confirm="deleteForm('删除数据表')"
                >
                  <a href="#">删除数据表</a>
                </a-popconfirm>
              </span>
            </a-menu-item>
          </a-menu>
        </a-dropdown-button>
        <a-dropdown-button @click="handleButtonClick" v-if="false">
          更多操作
          <a-menu slot="overlay" @click="()=>{}">
            <a-menu-item key="1"> <a-icon type="download" />模型下载</a-menu-item>
            <a-menu-item key="2"> <a-icon type="cloud-upload" />模型导入</a-menu-item>
            <a-menu-item key="3"> <a-icon type="cloud-download" />模型导出</a-menu-item>
          </a-menu>
        </a-dropdown-button>
      </div> -->
      <div class="table-content">
        <FilterTable
          ref="table"
          :columns="columns"
          :dataSource="dataSource"
          :total="total"
          @changeParams="changeParams"
        />
      </div>
    </div>
    <a-modal v-model="modalVisible" title="新建模型" :footer="null" :destroyOnClose="true" @ok="handleOk">
      <FormModelAdd ref="model" :treeData="treeData" :catalogId="catalogId" @handleOk="handleOk" />
    </a-modal>
    <a-modal
      v-model="deleteModalVisible"
      :title="title"
      :footer="null"
      :destroyOnClose="true"
      @ok="deleteModelHandleOk"
    >
      <a-form-model-item
        has-feedback
        label="请输入密码"
        prop="pass"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
      >
        <a-input v-model="password" type="password" autocomplete="off" />
      </a-form-model-item>
      <a-form-model-item :wrapper-col="{ span: 12, offset: 8 }">
        <a-button type="stop" style="margin-right: 20px" @click="deleteModelHandleOk"> 取消 </a-button>
        <a-button type="add" @click="onSubmitDeleteForm(title)"> 确定 </a-button>
      </a-form-model-item>
    </a-modal>
    <a-modal
      v-model="createdTableViable"
      title="创建数据表"
      :footer="null"
      :destroyOnClose="true"
      width="80vw"
      @ok="createdTableHandleOk"
    >
      <a-tabs default-active-key="1">
        <a-tab-pane key="1" tab="变更的属性">
          <FormModelCreate ref="FormModelCreate" :dataSource="dataSourceFormModelCreate" :total="totalChangeTable" />
        </a-tab-pane>
        <a-tab-pane key="2" tab="新增的属性">
          <FilterTable
            ref="table2"
            :isSelected="false"
            :columns="columnsTableNews"
            :dataSource="dataSourceTableNews"
            :total="total"
          />
        </a-tab-pane>
      </a-tabs>
      <a-form-model-item :wrapper-col="{ span: 12, offset: 8 }">
        <a-button type="stop" style="margin-right: 20px" @click="createdTableHandleOk"> 取消 </a-button>
        <a-button type="add" @click="confirmCreateTable"> 确定 </a-button>
      </a-form-model-item>
    </a-modal>
  </div>
</template>

<script type="text/ecmascript-6">
import FilterTable from '@/components/filterTable'
import FormModelAdd from './components/FormModelAdd'
import FormModelCreate from './components/FormModelCreate'
import { getClassTreeApi } from '@/api/model/kindManger'
import {
  getModelListApi,
  removeModelApi,
  deleteDropTable,
  createTableApi,
  createTableAgainApi
} from '@/api/model/modelManger'
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)
    }
  }
}
export default {
  // beforeRouteEnter(to, from, next) {
  //   next(vm => {
  //     vm.from = from
  //   })
  // },
  beforeRouteLeave(to, from, next) {
    // 销毁组件，避免通过vue-router再次进入时，仍是上次的history缓存的状态
    this.$destroy(true)
    next()
  },
  components: {
    FilterTable,
    FormModelAdd,
    FormModelCreate
  },
  data() {
    var vm = this
    return {
      treeData: [],
      // dataList: [],
      modalVisible: false,
      deleteModalVisible: false,
      createdTableViable: false,
      expandedKeys: [],
      autoExpandParent: true,
      searchValue: '',
      dataSource: [],
      dataSourceTableNews: [],
      dataSourceFormModelCreate: [],
      total: 0,
      totalChangeTable: 0,
      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',
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender'
          },
          ellipsis: true
        },
        {
          title: '模型代码',
          dataIndex: 'modelCode',
          key: 'modelCode',
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender'
          }
        },
        {
          title: '所属分类',
          dataIndex: 'catalogName',
          key: 'catalogName',
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender'
          }
        },
        {
          title: '列表详情页',
          dataIndex: 'listPageStatus',
          key: 'listPageStatus',
          customRender: (text, record, index) => {
            var child = vm.$createElement('button', {
              domProps: {
                innerHTML: text === '0' ? '未发布' : '已发布'
              },
              on: {
                click: function() {
                  vm.goTableGeneration(record)
                }
              },
              style: {
                cursor: 'pointer'
              }
            })
            var obj = {
              children: child,
              attrs: {}
            }
            return obj
          }
        },
        {
          title: '表单详情页',
          dataIndex: 'formStatus',
          key: 'formStatus',
          customRender: (text, record, index) => {
            var child = vm.$createElement('button', {
              domProps: {
                innerHTML: text === '0' ? '未发布' : '已发布'
              },
              on: {
                click: function() {
                  vm.goFormGeneration(record)
                }
              },
              style: {
                cursor: 'pointer'
              }
            })
            var obj = {
              children: child,
              attrs: {}
            }
            return obj
          }
        }
        //   {
        //     title: '参考标准文件',
        //     dataIndex: 'fileName',
        //     key: 'fileName',
        //     scopedSlots: {
        //       filterDropdown: 'filterDropdown',
        //       filterIcon: 'filterIcon',
        //       customRender: 'customRender'
        //     }
        //   },
        //   {
        //     title: '模型描述',
        //     dataIndex: 'modelDesc',
        //     key: 'modelDesc',
        //     scopedSlots: {
        //       filterDropdown: 'filterDropdown',
        //       filterIcon: 'filterIcon',
        //       customRender: 'customRender'
        //     }
        //   },
        //   {
        //     title: '创建人',
        //     dataIndex: 'createBy',
        //     key: 'createBy',
        //     scopedSlots: {
        //       filterDropdown: 'filterDropdown',
        //       filterIcon: 'filterIcon',
        //       customRender: 'customRender'
        //     }
        //   },
        //   {
        //     title: '创建时间',
        //     dataIndex: 'createTime',
        //     key: 'createTime',
        //     scopedSlots: {
        //       filterDropdown: 'filterDropdown',
        //       filterIcon: 'filterIcon',
        //       customRender: 'customRender'
        //     }
        //   },
        //   {
        //     title: '数据表状态',
        //     dataIndex: 'tableStatus',
        //     key: 'tableStatus',
        //     customRender: (text, record, index) => {
        //       if (text === '0') {
        //         return (<span style="color:#69c0ff">已创建</span>)
        //       } else {
        //         return (<span style="color:#f03e3e">未创建</span>)
        //       }
        //     },
        //     align: 'center',
        //     scopedSlots: {
        //       filterDropdown: 'filterDropdown',
        //       filterIcon: 'filterIcon'
        //     }
        //   }
      ],
      columnsTableNews: [
        {
          title: '序号',
          dataIndex: 'orderNum',
          key: 'sort',
          width: 60,
          align: 'center',
          customRender: (text, record, index) => {
            return <span>{++index}</span>
          }
        },
        {
          title: '属性代码',
          dataIndex: 'attrCode',
          key: 'attrCode'
        },
        {
          title: '属性名称',
          dataIndex: 'attrName',
          key: 'attrName',
          ellipsis: true
        },
        {
          title: '属性类型',
          dataIndex: 'attrType',
          key: 'attrType'
        },
        {
          title: '数据长度',
          dataIndex: 'dataLength',
          key: 'dataLength'
        },
        {
          title: '数值精度',
          dataIndex: 'dataPrecision',
          key: 'dataPrecision'
        },
        {
          title: '是否必填',
          dataIndex: 'ifRequired',
          key: 'ifRequired',
          customRender: (text, record, index) => {
            if (text === '0') {
              return <span>必填</span>
            } else {
              return <span>非必填</span>
            }
          }
        },
        {
          title: '是否唯一项',
          dataIndex: 'ifOnly',
          key: 'ifOnly',
          customRender: (text, record, index) => {
            if (text === '0') {
              return <span>唯一</span>
            } else {
              return <span>不唯一</span>
            }
          }
        },
        {
          title: '控件类型',
          dataIndex: 'ctrlsType',
          key: 'ctrlsType',
          customRender: (text, record, index) => {
            if (text === '0') {
              return <span>文本框</span>
            } else if (text === '1') {
              return <span>下拉框</span>
            } else if (text === '2') {
              return <span>时间日期选择框</span>
            }
          }
        },
        {
          title: '编码规则',
          dataIndex: 'codingIstrue',
          key: 'codingIstrue',
          customRender: (text, record, index) => {
            if (text === '0') {
              return <span>已编码</span>
            } else {
              return <span style="color:#f03e3e">未编码</span>
            }
          }
        },
        {
          title: '数据表状态',
          dataIndex: 'tableattrStatus',
          key: 'tableattrStatus',
          align: 'center',
          customRender: (text, record, index) => {
            if (text === '0') {
              return <span>已创建</span>
            } else if (text === '1') {
              return <span style="color:#f03e3e">未创建</span>
            } else if (text === '2') {
              return <span>已变更未同步</span>
            }
          }
        }
      ],
      password: '',
      params: {
        pageSize: 10,
        pageNum: 1
      },
      catalogId: '0',
      title: '删除模型'
    }
  },
  mounted() {
    this.getClassTree()
  },
  methods: {
    goTableGeneration(item) {
      this.$router.push({
        path: '/FormGeneration/list',
        query: {
          id: item.id
        }
      })
    },
    goFormGeneration(item) {
      this.$router.push({
        path: '/FormGeneration/form',
        query: {
          id: item.id
        }
      })
    },
    addAttr(data) {
      data.map((item) => {
        item.scopedSlots = { title: 'catalogName' }
        if (item.children) this.addAttr(item.children)
      })
      return data
    },
    getClassTree() {
      getClassTreeApi().then((res) => {
        if (res.code === 200) {
          this.treeData = this.addAttr(res.data.rows)
          generateList(this.treeData)
        }
      })
    },
    getTableList() {
      const { catalogId } = this
      getModelListApi({ catalogId, ...this.params }).then((res) => {
        if (res.code === 200) {
          this.dataSource = res.rows
          this.$refs.table.selectedRows = []
          this.$refs.table.selectedRowKeys = []
        }
      })
    },
    onSearch(e) {
      const value = e.target.value
      // console.log(`dataList---`, dataList)
      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)
      console.log(`expandedKeys`, expandedKeys)
      Object.assign(this, {
        expandedKeys,
        searchValue: value,
        autoExpandParent: true
      })
    },
    onExpandCloseAll() {
      this.expandedKeys = []
    },
    onExpandOpenAll() {
      this.expandedKeys = []
    },
    onClassSelect(selectedKeys, info) {
      this.catalogId = selectedKeys[0]
      selectedKeys[0] && this.getTableList()
      info.node.onExpand()
      console.log('selected', selectedKeys, info)
    },
    onExpand(selectedKeys) {
      this.expandedKeys = selectedKeys
      // console.log('Trigger Expand', selectedKeys, this.expandedKeys)
    },
    addForm() {
      this.modalVisible = true
      setTimeout(() => {
        this.$refs.model.submitType = 'add'
      }, 300)
    },
    editForm() {
      this.modalVisible = true
      setTimeout(() => {
        this.$refs.model.form = Object.assign({}, this.$refs.table.selectedRows[0])
        this.$refs.model.submitType = 'edit'
      }, 300)
    },
    deleteForm(title) {
      this.title = title
      this.deleteModalVisible = true
    },
    onSubmitDeleteForm(title) {
      const { password } = this
      const { id, tableStatus } = this.$refs.table.selectedRows[0]
      if (title === '删除模型') {
        // this.title = '删除模型'
        removeModelApi({ id, password }).then((res) => {
          if (res.code === 200) {
            this.$message.info('删除成功')
            this.getTableList()
            this.deleteModalVisible = false
          } else {
            this.$message.error('删除失败')
            this.getTableList()
            this.deleteModalVisible = false
          }
        })
      } else {
        if (tableStatus === '1') {
          this.$message.error('未创建禁止删除')
        } else {
          deleteDropTable({ id, password }).then((res) => {
            if (res.code === 200) {
              this.$message.info('删除成功')
              this.getTableList()
              this.deleteModalVisible = false
            } else {
              this.$message.error('删除失败')
              this.getTableList()
              this.deleteModalVisible = false
            }
          })
        }
      }
    },
    handleOk() {
      this.modalVisible = false
      this.getTableList()
      this.getClassTree()
    },
    deleteModelHandleOk() {
      this.deleteModalVisible = false
    },
    confirmCreateTable() {
      // 确定创建数据表
      const { id } = this.$refs.table.selectedRows[0]
      createTableAgainApi({ id }).then((res) => {
        this.createdTableViable = false
        if (res.code === 200) {
          this.$message.info(res.msg)
          this.getTableList()
        }
      })
    },
    handleButtonClick(e) {
      console.log('click left button', e)
    },
    createTable(e) {
      const { key } = e
      const { id } = this.$refs.table.selectedRows[0]
      if (key === '1') {
        createTableApi({ id }).then((res) => {
          if (res.code === 200) {
            if (res.isCreated === '1') {
              this.createdTableViable = true
              this.dataSourceFormModelCreate = res.data.change
              this.dataSourceTableNews = res.data.news
            } else {
              this.getTableList()
              this.$message.info(res.msg)
            }
          }
        })
      }
    },
    createdTableHandleOk() {
      this.createdTableViable = false
    },
    changeParams(key, value) {
      this.$set(this.params, key, value)
    }
  },
  watch: {
    params: {
      deep: true,
      immediate: true,
      handler(val) {
        this.getTableList()
      }
    }
  }
}
</script>

<style lang="less">
@import url('../_style/index.less');
.ant-modal-body {
  // padding: 0 0 40px 0;
  padding-top: 0;
}
button{
    background: none;
    border: none;
    display: inline-block;
    margin: 0 5px;
    padding: 0;
    box-shadow: none;
  }
  .ant-table-tbody > tr > td button{
    color: #2f54eb;
  }
</style>
