<template>
  <div>
    <el-dialog ref="dialogTable" title="新增盘点单" :visible="crud.status.cu > 0" append-to-body :close-on-click-modal="false" :modal-append-to-body="false" :before-close="crud.cancelCU">
      <span class="dialog-right-top" />
      <span class="dialog-left-bottom" />
      <div class="setting-dialog">
        <el-form ref="form" :model="form" size="small" inline label-width="80px" :rules="rules">
          <el-form-item label="选择区域" prop="selectAreaValue" style="margin-right: 10px;">
            <treeselect
              v-model="form.selectAreaValue"
              :options="selectAreaOptions"
              multiple
              placeholder="请选择(单选)"
              style="width: 184px;"
              :limit="1"
              :limit-text="count => `+${count}`"
            />
          </el-form-item>
          <el-form-item label="选择门类" prop="categoryValue" style="margin-right: 10px;">
            <treeselect
              ref="treeselect"
              v-model="form.categoryValue"
              flat
              :multiple="false"
              placeholder="请选择(单选)"
              :options="category"
              style="width: 184px;"
              :normalizer="normalizer"
              :default-expand-level="2"
              @select="node=>treeSelectInput(node)"
            />
          </el-form-item>
          <el-form-item label="选择年度" prop="archiveYears" style="margin-right: 0;">
            <el-select
              v-model="form.archiveYears"
              style="width: 184px;"
              multiple
              filterable
              clearable
              placeholder="请选择(可多选)"
              :collapse-tags="showTags"
              @change="changeSelect"
              @remove-tag="removeTag"
            >
              <el-option v-if="yearsOptions.length !== 0" label="全选" value="全选" @click.native="selectAll" />
              <el-option
                v-for="item in yearsOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="盘点方式" prop="arrangeType">
            <el-select
              v-model="form.arrangeType"
              style="width: 184px;"
              clearable
              placeholder="请选择(单选)"
            >
              <el-option
                v-for="item in checkOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-button class="check-confirm-btn" type="primary" size="mini" @click="handleBuild"><i class="iconfont icon-shengchengpandiandan" />生成盘点单</el-button>
        </el-form>
        <el-table v-if="isCaseOrFile === 2" v-loading="loading" :data="tableData" height="400px" :cell-class-name="cell">
          <el-table-column type="index" align="center" label="序号" width="80" />
          <el-table-column align="center" label="状态" width="100">
            <template>
              <!-- 未盘点 -->
              <span class="clear">未盘点</span>
            </template>
          </el-table-column>
          <el-table-column prop="child" align="center" label="子条数目" width="100" />
          <el-table-column prop="categoryType" align="center" label="门类级别" width="100">
            <template slot-scope="scope">
              <span v-if="scope.row.categoryType === 5" style="width:56px">文件级</span>
              <span v-if="scope.row.categoryType === 4" style="width:56px">卷内级</span>
              <span v-if="scope.row.categoryType === 3" style="width:56px">案卷级</span>
            </template>
          </el-table-column>
          <el-table-column prop="categoryName" align="center" show-overflow-tooltip label="门类名称" width="120" />
          <el-table-column prop="fondsNo" align="center" label="全宗号" width="180" show-overflow-tooltip />
          <el-table-column prop="archiveNo" align="center" label="档号" width="180" show-overflow-tooltip />
          <el-table-column prop="archiveYear" align="center" label="归档年度" width="100" />
          <el-table-column prop="maintitle" show-overflow-tooltip label="题名" align="center" width="180" />
          <el-table-column prop="securityClass" label="保密程度" align="center" width="85" />
          <el-table-column prop="department" label="部门" align="center" width="120" />
          <el-table-column prop="caseName" label="盒名称" show-overflow-tooltip align="center" width="120" />
          <el-table-column prop="folderLocationDetails" show-overflow-tooltip label="所在位置" align="center" width="300">
            <template slot-scope="scope">
              <span v-if="!scope.row.folderLocationDetails">-</span>
              <span v-else>
                <el-tag effect="dark">{{ scope.row.folderLocationDetails }}</el-tag>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="create_time" label="创建时间" align="center" width="150">
            <template slot-scope="scope">
              <div>{{ scope.row.create_time | parseTime }}</div>
            </template>
          </el-table-column>
        </el-table>

        <el-table
          v-if="isCaseOrFile === 1"
          ref="table"
          v-loading="loading"
          :cell-class-name="cell"
          :data="tableData"
          height="400px"
          style="width: 100%;"
          @row-dblclick="handleCaseDbClick"
        >
          <el-table-column type="index" label="序号" width="55" align="center" />
          <el-table-column align="center" label="状态" width="100">
            <template>
              <!-- 未盘点 -->
              <span class="clear">未盘点</span>
            </template>
          </el-table-column>
          <el-table-column prop="depositNum" label="已装" align="center" min-width="56" />
          <el-table-column prop="caseName" label="盒名称" :show-overflow-tooltip="true" align="center" min-width="190" />
          <el-table-column prop="tid" label="电子标签" align="center" min-width="180" />
          <el-table-column prop="barcode" label="条形码" align="center" min-width="120" />
          <el-table-column label="存放位置" align="center" min-width="300">
            <template slot-scope="scope">
              <span v-if="!scope.row.folderLocationDetails">-</span>
              <span v-else>
                <el-tag effect="dark">{{ scope.row.folderLocationDetails }}</el-tag>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="update_time" width="175" label="操作时间" align="center">
            <template slot-scope="scope">
              <div>{{ scope.row.update_time | parseTime }}</div>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination v-if="tableData.length !== 0" :page-size.sync="page.size" :total="page.total" :current-page.sync="page.page" style="margin-top: 8px;" layout="total, prev, pager, next, sizes" @size-change="sizeChangeHandler($event)" @current-change="pageChangeHandler" />
        <div v-if="tableData.length !== 0" slot="footer" class="dialog-footer">
          <el-button :disabled="!(tableData.length)" @click="handleSave">保存</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 档案盒详情 -->
    <detailDialog ref="detailDom" />
  </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { menu } from '@/api/storeManage/levelManage/level'
import { FetchCategoryMenu } from '@/api/system/category/category'
import { previewArrange, addArrange } from '@/api/archivesManage/archivesCheck'
import { FetchInitContorlView } from '@/api/archivesManage/library'
import { findInCase } from '@/api/archivesManage/caseManage'
import { crud, form } from '@crud/crud'
import detailDialog from '../../caseManage/caseList/module/detailDialog'
const defaultForm = {
  selectAreaValue: [],
  categoryValue: null,
  archiveYears: [],
  arrangeType: null
}
export default {
  name: 'AddCheck',
  components: { Treeselect, detailDialog },
  mixins: [
    crud(),
    form(function() {
      return Object.assign({ }, defaultForm)
    })
  ],
  data() {
    return {
      loading: false,
      menusIds: [],
      tableData: [],
      isCaseOrFile: 0,
      addFormVisible: false,
      selectAreaOptions: [],
      nodeKey: 'id',
      defaultCheckedKeys: [],
      oldCategory: [],
      allCategory: [],
      category: [],
      showTags: true,
      yearsOptions: [],
      checkOptions: [
        {
          label: '按盒盘点(H)',
          value: 1
        },
        {
          label: '按件盘点(J)',
          value: 2
        }
      ],
      page: {
        total: 0,
        size: 10,
        page: 1
      },
      params: {
        page: null,
        size: null,
        deviceIds: null,
        categoryIds: null
      },
      rules: {
        selectAreaValue: [{ required: true, trigger: 'change', message: '请选择区域' }],
        categoryValue: [{ required: true, trigger: 'change', message: '请选择门类' }],
        archiveYears: [{ required: true, trigger: 'change', message: '请选择年度' }],
        arrangeType: [{ required: true, trigger: 'change', message: '请选择盘点方式' }]
      }
    }
  },
  created() {
    this.getTreeMenu()
    this.getCategoryDataTree()
  },
  methods: {
    getTreeMenu() {
      menu().then(data => {
        const deviceTree = []
        let storeroom = {}
        let devices = []
        data.forEach((item, i) => {
          if (!storeroom.id) {
            item.storeroomId.label = item.storeroomId.name
            storeroom = item.storeroomId
            item.label = item.deviceName
            devices.push(item)
          } else if (storeroom.id !== item.storeroomId.id) {
            item.storeroomId.label = item.storeroomId.name
            storeroom.children = devices
            deviceTree.push(storeroom)
            devices = []
            item.label = item.deviceName
            devices.push(item)
            storeroom = item.storeroomId
          } else {
            item.storeroomId.label = item.storeroomId.name
            item.label = item.deviceName
            devices.push(item)
          }
          if (i === data.length - 1) {
            item.storeroomId.label = item.storeroomId.name
            storeroom.children = devices
            deviceTree.push(storeroom)
          }
          this.selectAreaOptions = deviceTree
        })
      })
    },
    filterData(data) {
      return data.filter(node => {
        if (node.children && node.children.length > 0) {
          node.children = this.filterData(node.children) // 递归处理子节点
        }
        return node.isType !== 3 // 过滤掉isType为3的节点
      })
    },
    getCategoryDataTree() {
      FetchCategoryMenu().then(res => {
        this.category = this.filterData(res)
      })
    },
    treeSelectInput(value) {
      console.log(value)
      this.form.categoryValue = value.id
      if (this.form.categoryValue) {
        let categoryLevel = null
        if (value.arrangeType === 1) {
          categoryLevel = 3
        } else if (value.arrangeType === 2) {
          categoryLevel = 2
        } else {
          categoryLevel = 1
        }
        this.getYear(categoryLevel)
      } else {
        this.yearsOptions = []
        this.form.archiveYears = []
      }
    },
    getYear(categoryLevel) {
      const params = {
        'categoryId': this.form.categoryValue,
        'categoryLevel': categoryLevel,
        'ignore': false,
        'isdel': false,
        'page': 0,
        'size': 10
      }
      FetchInitContorlView(params).then(data => {
        if (data) {
          this.yearsOptions = data.yearGroup.map(item => {
            const json = {}
            json.value = item
            json.label = item
            return json
          })
        }
      })
    },
    selectAll() {
      if (this.form.archiveYears.length < this.yearsOptions.length) {
        this.form.archiveYears = []
        this.yearsOptions.map((item) => {
          this.form.archiveYears.push(item.value)
        })
        this.form.archiveYears.unshift('全选')
      } else {
        this.form.archiveYears = []
      }
    },
    changeSelect(val) {
      if (!val.includes('全选') && val.length === this.yearsOptions.length) {
        this.form.archiveYears.unshift('全选')
      } else if (val.includes('全选') && (val.length - 1) < this.yearsOptions.length) {
        this.form.archiveYears = this.form.archiveYears.filter((item) => {
          return item !== '全选'
        })
      }
    },
    removeTag(val) {
      if (val === '全选') {
        this.form.archiveYears = []
      }
    },
    // 生成盘点单
    handleBuild() {
      this.$refs['form'].validate(valid => {
        if (!valid) {
          return
        }
        this.loading = true
        const paramsNo = this.getParams()
        this.params.deviceIds = paramsNo.deviceIds
        this.params.categoryIds = paramsNo.categoryIds
        this.params.arrangeType = paramsNo.arrangeType
        this.params.archiveYears = paramsNo.archiveYears
        this.params.page = this.page.page - 1
        this.params.size = this.page.size
        this.doPreArrange(this.params)
      })
    },
    handleSave() {
      const params = this.getParams()
      // 新增盘点
      addArrange(params).then(res => {
        // this.tableData = res.detaills
        if (res) {
          this.crud.refresh()
          this.$message({
            message: '新增成功',
            type: 'success'
          })
          this.addFormVisible = false
          this.crud.refresh()
        } else {
          this.$message.error('新增失败')
        }
      })
    },
    getParams() {
      const room = this.selectAreaOptions.map(item => { return item.id }) // 所有区域id
      if (this.form.selectAreaValue.length > 0 && this.form.categoryValue.length > 0) {
        let deviceIds = this.form.selectAreaValue.filter(item => !room.includes(item)) // 选中的设备id
        const devIds = JSON.parse(JSON.stringify(deviceIds))
        let region = []
        this.selectAreaOptions.forEach(item => {
          if (this.form.selectAreaValue.includes(item.id)) {
            region.push(item.name)
            const arr = item.children.map(val => { return val.id }) // 区域内所有设备
            deviceIds = deviceIds.concat(arr)
          }
          if (devIds.length > 0) {
            item.children.forEach(val => {
              if (devIds.includes(val.id) && !region.includes(item.name)) {
                region.push(item.name) // 含设备的区域
              }
            })
          }
        })
        region = region.join(',') // 区域str
        // const categoryIds = this.form.categoryValue.filter(item => item !== 0)

        if (this.form.arrangeType === 1) {
          this.isCaseOrFile = 1
        } else {
          this.isCaseOrFile = 2
        }

        let archiveYearsValue
        if (this.form.archiveYears.includes('全选')) {
          archiveYearsValue = null
        } else {
          archiveYearsValue = this.form.archiveYears.join(',')
        }

        const categoryIds = []
        categoryIds.push(this.form.categoryValue)
        const params = {
          'categoryIds': categoryIds,
          'deviceIds': deviceIds,
          'region': region,
          'arrangeType': this.form.arrangeType,
          'archiveYears': archiveYearsValue
        }
        return params
      }
    },
    // 预盘点
    doPreArrange(params) {
      previewArrange(params).then(res => {
        this.tableData = res.content
        this.page.total = res.totalElements
        this.loading = false
      })
    },
    // 每页条数改变
    sizeChangeHandler(e) {
      this.loading = true
      this.page.size = e
      this.page.page = 1
      this.params.size = e
      this.params.page = 0
      this.doPreArrange(this.params)
      this.loading = false
    },
    // 当前页改变
    pageChangeHandler(e) {
      this.loading = true
      this.page.page = e
      this.params.page = e - 1
      this.doPreArrange(this.params)
      this.loading = false
    },
    // 单元格样式
    cell({ row, columnIndex }) {
      if (columnIndex === 1) {
        return 'fail-clear'
      }
    },
    handleCaseDbClick(row) {
      this.$refs.detailDom.caseTabIndex = 0
      this.$refs.detailDom.rowData = row
      const params = {
        caseId: row.id
      }
      findInCase(params).then(res => {
        console.log(res)
        if (res) {
          this.$refs.detailDom.tableData = res.archives_o
          this.$refs.detailDom.queryFields = res.field_o
          this.$refs.detailDom.queryCnFields = res.cnField_o
          this.$refs.detailDom.collectLevel = parseInt(res.archives_o[0].categoryLevel)
        } else {
          this.$refs.detailDom.tableData = []
        }
      })
      this.$refs.detailDom.detailVisible = true
    },
    handleClose() {
      this.getTreeMenu()
      this.getCategoryDataTree()
      this.tableData = []
      this.isCaseOrFile = 0
      this.$refs['form'].resetFields()
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.cnName,
        children: node.children,
        isDisabled: node.isType !== 2
      }
    }

  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog{
  width: 864px;
  .el-dialog__body .el-form-item .el-form-item__content{
    width: 184px !important;
  }
  .el-form{
    position: relative;
  }
  .check-confirm-btn{
    position: absolute;
    right: 5px;
    bottom: 20px;
  }
}
// @import '~@/assets/styles/lend-manage.scss';

// .el-form{
//   display: flex;
//   flex-wrap: wrap;
//   padding-left: 12px;
// }
// ::v-deep .el-dialog{
//   width: 1000px;
//   // height: 520px;
// }
// ::v-deep .el-dialog .el-dialog__header .el-dialog__close::before{
//   position: absolute;
//   right: -190px;
//   bottom: -12px;
// }
// ::v-deep .el-dialog__body{
//   padding: 30px 0;
// }
// ::v-deep .el-dialog .dialog-footer{
//   margin: 0 auto !important;
// }
// ::v-deep .el-tag.el-tag--info{
//   height: 24px !important;
//   line-height: 24px !important;
// }
// ::v-deep .el-input__inner{
//   height: 30px !important;
// }
// //滚动条
// ::v-deep ::-webkit-scrollbar-corner{
//   background: transparent;
// }
// // 树形选择器
// ::v-deep .vue-treeselect__placeholder, .vue-treeselect__single-value{
//   line-height: 30px;
// }
// ::v-deep .vue-treeselect--has-value .vue-treeselect__multi-value{
//   margin-bottom: 0;
// }
// ::v-deep .vue-treeselect__multi-value-item-container{
//   padding-top: 2px;
//   line-height: 20px;
// }

// ::v-deep .el-dialog .el-form .vue-treeselect__control{
//   height: 30px !important;
//   line-height: 18px;
// }
// ::v-deep .vue-treeselect__limit-tip{
//   background: #13439E;
//   border-radius: 3px;
//   margin: 2px;
//   padding: 0 3px;
//   .vue-treeselect__limit-tip-text{
//     padding: 2px 2px;
//     color: #fff;
//   }
// }
</style>
