<template>
  <div id="addingMasterData">
    <div class="tree-wrap" v-if="showTree">
      <h2>主数据分类</h2>
      <div class="title">
        <a-input-search
          placeholder="请输入类别名称/代码"
          style="width: 200px"
          @change="onSearch" />
        <div class="action">
          <div @click="onExpandCloseAll">全部收起</div>
        </div>
      </div>
      <a-tree
        v-if="treeData.length>0"
        :replaceFields="{
          title:'name',
          key: 'id',
          children:'children',
          value:'id'
        }"
        show-line
        :defaultExpandAll="true"
        :expandedKeys="expandedKeys"
        :auto-expand-parent="autoExpandParent"
        :tree-data="treeData"
        @expand="onExpand"
        @select="onClassSelect">
        <template slot="name" slot-scope="{ name }">
          <span v-if="name.indexOf(searchValue) > -1">
            {{ name.substr(0, name.indexOf(searchValue)) }}
            <span style="color: #f50">{{ searchValue }}</span>
            {{ name.substr(name.indexOf(searchValue) + searchValue.length) }}
          </span>
          <span v-else>{{ name }}</span>
        </template>
        <a-icon slot="switcherIcon" type="down" />
      </a-tree>
    </div>
    <div class="table-wrap" ref="table_wrap">
      <div class="header">
        <div class="title">主数据新增</div>
        <div>模型:{{ modelName }}</div>
        <div>代码:{{ modelCode }}</div>
        <div class="change-view" @click="goModelView"><a-icon type="swap" /></div>
      </div>
      <div class="main">
        <div class="table-operations">
          <a-button type="add" @click="addFun">新增数据</a-button>
          <a-button type="delete" :disabled="!hasSelected" @click="deleteFun(selectedRowsId)">删除</a-button>
          <a-button type="delete" :disabled="!onCancel" @click="cancel(selectedRowsId)">撤消</a-button>
          <a-button type="edit" :disabled="!oneHasSelected" @click="updateFun">编辑</a-button>
          <a-button type="view" :disabled="!onJournal" @click="getApproveLogList(selectedRowsId)">审批日志</a-button>
          <a-button type="work" :disabled="!stopHasSelected" @click="getFile(selectedRowsId)">提交</a-button>
          <a-dropdown-button @click="handleButtonClick">
            更多操作
            <a-menu slot="overlay" @click="handleMenuClick" >
              <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>
          </a-dropdown-button>
        </div>
        <Table
          @getSelectedRowKeys="getSelectedRowKeys"
          :tableData="tableData"
          :columns="columns"
          :selectedRowKeys="selectedRowKeys"
          :selectedRows="selectedRows"
          :total="total"
          @changeParams="changeParams"
          :statusFormat="statusFormat"
        />
      </div>
      <a-modal
        width="50vw"
        v-model="showState"
        title="主数据新增"
        :destroyOnClose="true"
        :footer="null"
        @ok="handleOk">
        <FormAdd
          :modelId="modelId"
          :selectedRows="selectedRowsOne"
          @getShowState="getShowState"
          @handleOk="handleOk"
          :recordId="this.selectedRowsOne.recordId"
          :ischange="ischange"
          :modelCode="modelCode"
          @getAddList="getAddList"
          :addChange="addChange"
          @clearSelectedRows="clearSelectedRows"
          :id="this.selectedRowsOne.id"
        />
        <!-- <Add
          :selectedRows="selectedRowsOne"
          @getShowState="getShowState"
          @handleOk="handleOk"
          :changesFrom="changesFrom"
          :modelId="modelId"
          :modelCode="modelCode"
          @getAddList="getAddList"
          :recordId="this.selectedRowsOne.recordId"
          :id="this.selectedRowsOne.id"
          :ischange="ischange"
          :addChange="addChange"
          @clearSelectedRows="clearSelectedRows"
        /> -->
      </a-modal>
      <a-modal
        width="1100px"
        v-model="showJournal"
        title="审批日志"
        :footer="null"
        :destroyOnClose="true"
        @ok="getShowJournal">
        <journal
          :statusFormat="statusFormat"
          :journalDate="journalDate"
          @getShowJournal="getShowJournal"
          :tableData="showlista"
          :operationFormat="operationFormat"
        />
      </a-modal>
      <!-- 上传文件 -->
      <import-excel
        ref="importExcel"
        @ok="getAddList"
        :modelId="modelId"
      />
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
import Table from './components/Table'
import Add from './components/add.vue'
import FormAdd from './components/FormAdd.vue'
import ImportExcel from './components/ImportExcel.vue'
import journal from './components/journal.vue'
import {
  getList,
  removeMasterData,
  getApproveLog,
  recallMasterData,
  gsfwimportTemplate,
  mdDataBatchSub,
  // getAttrByModelId,
  getTreeDataByModelId
} from '@/api/masterDataManger/addingMasterData'
import { getFormModel } from '@/api/model/genenrteTable'
const basePath = '/modelView/modelView'
var id = null
var modelName = null
var Code = null
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.id === key)) {
        parentKey = node.id
      } 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 id = node.id
    const name = node.name
    dataList.push({ id, name: name })
    if (node.children) {
      generateList(node.children)
    }
  }
}
export default {
  beforeRouteEnter(to, from, next) {
    id = to.query.id
    modelName = to.query.modelName
    Code = to.query.modelCode
    if (!id) {
      next(
        { path: basePath,
          query: {
            redirectPath: to.path
          }
        }
      )
    } else {
      next()
    }
  },
  beforeRouteLeave(to, from, next) {
    // 销毁组件，避免通过vue-router再次进入时，仍是上次的history缓存的状态
    this.$destroy(true)
    next()
  },
  components: {
    Table,
    Add,
    FormAdd,
    journal,
    ImportExcel
  },
  data() {
    return {
      modelName,
      treeData: [],
      expandedKeys: [],
      autoExpandParent: true,
      searchValue: '',
      showTree: false,
      showlista: [],
      tableData: [],
      journalDate: [
        {
        title: '序号',
        dataIndex: 'attrSort',
        key: 'attrSort',
        align: 'center',
        width: 150,
        customRender: (text, record, index) => {
            return (<span>{++index}</span>)
          }
        },
        {
        title: '操作类型',
        dataIndex: 'operationType',
        key: 'operationType',
        scopedSlots: { customRender: 'operationType' }
        },
        {
        title: '审批状态',
        dataIndex: 'processStatus',
        key: 'processStatus',
        scopedSlots: { customRender: 'processStatus' }
        },
        {
        title: '审批意见',
        dataIndex: 'approveDesc',
        key: 'approveDesc'
        },
        {
        title: '审批人',
        dataIndex: 'approver',
        key: 'approver'
        },
        {
        title: '审批人电话',
        dataIndex: 'approverTel',
        key: 'approverTel'
      },
      {
        title: '送审时间',
        dataIndex: 'createTime',
        key: 'createTime'
        },
        {
        title: '审批时间',
        dataIndex: 'updateTime',
        key: 'updateTime'
        }
      ],
      selectedRowKeys: [],
      selectedRows: [],
      columns: [
      {
        title: '序号',
        dataIndex: 'attrSort',
        key: 'attrSort',
        align: 'center',
        fixed: 'left',
        width: 100,
        customRender: (text, record, index) => {
            return (<span>{++index}</span>)
          }
      },
      {
        title: '流程状态',
        dataIndex: 'processStatus',
        key: 'processStatus',
        align: 'center',
        fixed: 'left',
        width: 100,
        scopedSlots: {
          filterDropdown: 'filterDropdown',
          filterIcon: 'filterIcon',
          customRender: 'processStatus'
        }
      },
      {
        title: '审批意见',
        dataIndex: 'approveDesc',
        key: 'approveDesc',
        // fixed: 'left',
        // width: 150,
        ellipsis: true
      },
      {
        title: '创建人',
        dataIndex: 'createBy',
        key: 'createBy'
      },
       {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime'
        // fixed: 'right',
        // width: 100,
        // ellipsis: true

      },
      {
        title: '最后更新人',
        dataIndex: 'updateBy',
        key: 'updateBy'
      },
      {
        title: '最后更新时间',
        dataIndex: 'updateTime',
        key: 'updateTime',
        ellipsis: true

      }
      ],
      changesFrom: [],
      showState: false,
      showJournal: false,
      selectedRowsOne: {},
      selectedState: '',
      modelId: id,
      modelCode: Code,
      middleData: [],
      isDataProcessing: true,
      dataTemplate: {},
      ischange: '',
      statusOptions: [],
      operationTypeData: [],
      abcd: {},
      isSelect: Boolean,
      iscancel: Boolean,
      isSubmit: Boolean,
      total: 0,
      addChange: '',
      params: {
        pageSize: 10,
        pageNum: 1
      }
    }
  },
  computed: {
    hasSelected() {
      return this.selectedRowKeys.length > 0 && this.isSelect
    },
    onCancel() {
      return this.selectedRowKeys.length > 0 && this.iscancel
    },
    oneHasSelected() {
      return this.selectedRowKeys.length === 1 && this.isSelect
    },
    onJournal() {
      return this.selectedRowKeys.length === 1
    },
    stopHasSelected() {
      return this.selectedRowKeys.length > 0 && this.isSubmit
    }
  },
  created() {
    this.getTreeDataByModelId()
    this.getAddList()
    this.getTableHeader()
  },
  mounted() {
    this.getDicts('process_status_dict').then(response => {
      this.statusOptions = response.data
    })
    this.getDicts('operation_type_dict').then(response => {
      this.operationTypeData = response.data
    })
  },
  methods: {
    addAttr(data) {
      data.map((item) => {
        item.scopedSlots = { title: 'name' }
        if (item.children) this.addAttr(item.children)
      })
      return data
    },
    getTreeDataByModelId() { /* 获取树结构 */
      getTreeDataByModelId({ modelId: id }).then((res) => {
        if (res.code === 200) {
          this.showTree = !(+res.type)/* 是否显示树结构 */
          this.treeData = !(+res.type) ? this.addAttr(res.data) : []
          this.$refs['table_wrap'].style.width = !(+res.type) ? '74%' : '100%'
          generateList(this.treeData)
        }
      })
    },
     // 获取table表头
    getTableHeader() {
      getFormModel({ modelId: this.modelId }).then(res => {
        // console.log('%c [ res ]-460', 'font-size:13px; background:pink; color:#bf2c9f;', res)
        this.dataProcessing(res.data.column)
      })
    },
    clearSelectedRows() {
      const selectedRowKeys = []
      const selectedRows = []
      this.getSelectedRowKeys(selectedRowKeys, selectedRows)
    // console.log('清空啦！！！！！')
    },
    // 执行执行状态字典翻译
    statusFormat(row) {
      return this.selectDictLabel(this.statusOptions, row.processStatus)
    },
    operationFormat(row) {
      return this.selectDictLabel(this.operationTypeData, row.operationType)
    },
    // 模型下载
    handleMenuClick(e) {
      if (e.key === '1') {
        const data = {
        modelId: this.modelId
      }
      gsfwimportTemplate(data).then((res) => {
          this.download(res.msg)
      })
      } else if (e.key === '2') {
        this.$refs.importExcel.importExcelHandleOpen()
      }
    },
    // 获取数据
    getAddList() {
      const formData = new FormData()
      const obj = { ...this.params, modelId: id }
      Object.keys(obj).forEach((key) => {
        if (obj[key] instanceof Array) {
          obj[key].forEach((item) => {
            formData.append(key, item)
          })
          return
        }
        formData.append(key, obj[key])
      })
      getList(formData).then((res) => {
        if (res.code === 200) {
          this.total = res.total * 1
          this.tableData = res.rows
          this.dataProcessing2(res.rows)
        }
      })
    },
    // 删除数据
    deleteFun(id) {
      var that = this
      const formData = new FormData()
      formData.append('ids', id)
      formData.append('modelId', this.modelId)
      this.$confirm({
        title: '确认删除所选中数据?',
        onOk() {
          return removeMasterData(formData).then(() => {
            that.clearSelectedRows()
            that.getAddList()
            that.$message.success('删除成功', 3)
          })
        }
      })
    },
    // 审批日志
    getApproveLogList(id) {
      const formData = new FormData()
      formData.append('recordId', this.selectedRowsOne.recordId)
      formData.append('modelId', this.modelId)
      getApproveLog(formData).then((res) => {
        this.showlista = res.rows
      })
        this.showJournal = true
    },
    // 数据处理
    dataProcessing(data) {
      const arrs = []
      data.forEach((item, index) => {
        const obj1 = {}
        obj1.label = item.label
        obj1.prop = item.prop
        obj1.name = item.prop
        // obj1.width = 200
        obj1.id = index
        const obj2 = {}
        obj2.title = item.label
        obj2.dataIndex = item.prop
        obj2.key = item.prop
        // obj2.width = 200
        this.columns.splice(-4, 0, obj2)
        arrs.push(obj1)
      })
      // console.log(`this.columns`, JSON.stringify(this.columns))
      this.changesFrom = arrs
      // console.log('%c [ this.changesFrom ]-350', 'font-size:13px; background:pink; color:#bf2c9f;', this.changesFrom)
    },
    // 数据处理2
    dataProcessing2(data) {
      data.forEach(item1 => {
        Object.keys(JSON.parse(item1.logJson)).forEach(item2 => {
          item1[item2] = JSON.parse(item1.logJson)[item2]
        })
      })
    },
    // 撤消审核中的数据
    cancel(id) {
      var that = this
      const formData = new FormData()
      formData.append('ids', id)
      formData.append('modelId', this.modelId)
      this.$confirm({
        title: '确认撤消所选中数据?',
        onOk() {
          return recallMasterData(formData).then(() => {
            that.clearSelectedRows()
            that.getAddList()
            that.$message.success('撤消成功', 3)
          })
        }
      })
    },
    // 提交审核
    getFile() {
      const data = []
      this.selectedRows.forEach(item => {
        data.push({
        id: item.id,
        logJson: item.logJson,
        modelId: this.modelId,
        modelCode: this.modelCode,
        operationType: '0'
        })
      })
      mdDataBatchSub(data).then(res => {
        this.clearSelectedRows()
        this.getAddList()
        // console.log(`res`, res)
      })
    },
    // 模版下载
    handleButtonClick() {
    },
     // 提交判断
    isSubmits(data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].processStatus === '0') {
          this.isSubmit = true
        } else {
          this.isSubmit = false
          break
        }
      }
    },
    // 撤销删除判断
    isCancel(data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].processStatus === '2') {
          this.iscancel = true
        } else {
          this.iscancel = false
          break
        }
      }
    },
    // 多选删除判断
    isDelete(data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].processStatus === '2' || data[i].processStatus === '3') {
          this.isSelect = false
          break
        } else {
          this.isSelect = true
        }
      }
    },
    goModelView() {
      this.$router.push(
        { path: basePath,
          query: {
            redirectPath: this.$route.path
          }
        }
      )
    },
    getShowState(showState) {
      this.showState = showState
    },
    getShowJournal(showJournal) {
      this.showJournal = showJournal
    },

    addFun() {
      this.showState = true
      this.ischange = 'add'
      // console.log('this.showState: ', this.showState)
    },
    updateFun() {
      this.showState = true
      this.ischange = 'update'
      this.addChange = 'addchange'
      // console.log('this.showState: ', this.showState)
    },
    getSelectedRowKeys(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRowsId = []

      this.selectedRows = selectedRows
      this.abcd = selectedRows[(selectedRows.length - 1)]
      selectedRows.forEach((item) => {
        this.selectedRowsId.push(item.id)
      })
      // console.log('selectedRowsId: ', this.selectedRowsId)
      this.isDelete(selectedRows)
      this.isCancel(selectedRows)
      this.isSubmits(selectedRows)
      if (selectedRows.length === 1) {
        this.selectedRowsOne = selectedRows[(selectedRows.length - 1)]
        this.selectedState = this.selectedRowsOne.state
        // console.log('this.selectedState: ', this.selectedState)
        // console.log('this.selectedRowsOne: ', this.selectedRowsOne)
      } else {
        this.selectedState = ''
      }
    },
    handleOk() {
      this.showState = false
    },
    onSearch(e) { /* 搜索树结构 */
      const value = e.target.value
      const expandedKeys = dataList
      .map(item => {
        if (item.name.indexOf(value) > -1) {
          return getParentKey(item.id, this.treeData)
        }
        return null
      })
      .filter((item, i, self) => item && self.indexOf(item) === i)
      Object.assign(this, {
        expandedKeys,
        searchValue: value,
        autoExpandParent: true
      })
    },
    onExpandCloseAll() { /* 关闭所有树结构 */
      this.expandedKeys = []
    },
    onExpand(selectedKeys) { /* 父节点展开 */
      this.expandedKeys = selectedKeys
    },
    onClassSelect(selectedKeys, info) { /* 选择树结构 */
      selectedKeys[0] && this.$set(this.params, 'nodeId', selectedKeys[0])
      // selectedKeys[0] && this.getAddList()
      info.node.onExpand()
    },
    changeParams(key, value) {
      this.$set(this.params, key, value)
    }
  },
  watch: {
    params: {
      deep: true,
      immediate: false,
      handler(val) {
        this.getAddList()
      }
    }
  }

}
</script>

<style scoped lang="less">
#addingMasterData{
  padding: 20px;
  display: flex;
  justify-content: space-around;
  .tree-wrap{
    width: 25%;
    margin-right: 20px;
    background: #fff;
    padding: 20px;
    border-radius: 5px;
    h2{
      position: relative;
      color: #000;
			font-weight: 700;
			font-size: 20px;
      &::before{
        content: '';
        width: 4px;
        height: 26px;
        background-color: #3b75f5;
        position: absolute;
        left: -18px;
        top: 50%;
        transform: translateY(-50%);
      }
    }
  }
  .title{
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .action{
    display: flex;
    justify-content: space-around;
    >div{
      margin-left: 20px;
      cursor: pointer;
      &:hover{
        color: rgb(0, 101, 189);
      }
    }
  }
}
.table-wrap {
  min-width: calc(100% - 25%);
  max-width: 100%;
  width: auto;
  // max-width: 100%;
  background: #ffffff;
  border-radius: 5px;
  box-sizing: border-box;
  // padding: 25px 0;
  padding: 20px;
  box-shadow: 0 0 10px 0 rgba(17, 32, 65, 0.08);
	.header{
		display: flex;
		align-items: center;
		position: relative;
		padding: 0px 20px;
		&::before{
			content: '';
			width: 4px;
			height: 26px;
			background-color: #3b75f5;
			position: absolute;
			left: 0;
			top: 50%;
			transform: translateY(-50%);
		}
		>div{
			font-size: 18px;
			color: #777;
			margin-right: 14px;
			font-weight: 700;
		}
		.title{
			color: #000;
			font-weight: 700;
			font-size: 20px;
			margin-right: 20px;
		}
		.change-view{
			width: 32px;
			height: 32px;
			background: #fff;
      cursor: pointer;
			border-radius: 50%;
			text-align: center;
			line-height: 32px;
			font-size: 1.5em;
			font-weight: 700;
		}
	}
  .main {
    padding: 0 40px;
    .table-operations {
      margin: 30px 0 35px;

      .ant-btn-primary-disabled,
      .ant-btn-primary.disabled,
      .ant-btn-primary[disabled],
      .ant-btn-primary-disabled:hover,
      .ant-btn-primary.disabled:hover,
      .ant-btn-primary[disabled]:hover,
      .ant-btn-primary-disabled:focus,
      .ant-btn-primary.disabled:focus,
      .ant-btn-primary[disabled]:focus,
      .ant-btn-primary-disabled:active,
      .ant-btn-primary.disabled:active,
      .ant-btn-primary[disabled]:active,
      .ant-btn-primary-disabled.active,
      .ant-btn-primary.disabled.active,
      .ant-btn-primary[disabled].active {
        opacity: 0.3;
      }
    }
  }
}
</style>
