<template>
  <div>

    <div ref="lxHeader">
      <lx-header icon="md-apps" text="物资档案管理" style="margin-bottom: 10px; border: 0px; margin-top: 15px">
        <slot>
          <div style="display: flex;justify-content: flex-start;flex-wrap: wrap;">
            <el-input v-model="select.keyword" style="width: 200px;margin-right: 10px;" placeholder="关键词搜索" />
            <el-cascader v-model="select.fenlei" ref="cascaders" clearable popper-class="select_popper" style="width: 200px;margin-right: 10px;"
              :options="fenleiList" :props="{label:'name',value:'id'}" @change="(e)=>{changeFenlei(e)}" />
            <el-button type="primary" @click="getindex">查询</el-button>
            <el-button type="primary" style="margin-left: 10px;"
              @click="$refs['addMater'].isShow = true,$refs['addMater'].type = 'add'">添加</el-button>
            <el-button type="primary" style="margin-left: 10px;"
              @click="$refs['imports'].show()">导入</el-button>
            <el-button type="primary" style="margin-left: 10px;"
              @click="exportExcel(new Date().getTime().toString())">导出</el-button>
          </div>
        </slot>
      </lx-header>
    </div>

    <xy-table v-loading="loading" :list="list" :total="total" :table-item="table"
      @pageSizeChange="pageSizeChange" @pageIndexChange="pageChange">
      <template v-slot:btns>
        <el-table-column fixed="right" label="操作" width="220" header-align="center">
          <template slot-scope="scope">
            <div>
              <Button type="primary" size="small" @click="showMater(scope.row.id)">操作记录</Button>
              <Button type="primary" size="small" style="margin-left: 10px;"
                @click="editorMater(scope.row.id,'editor')">编辑</Button>
              <Poptip transfer confirm title="确认要删除吗？" @on-ok="deleteMater(scope.row)">
                <Button type="error" style="margin-left: 10px;" size="small" ghost>删除</Button>
              </Poptip>
            </div>

          </template>
        </el-table-column>
      </template>

    </xy-table>
    <addMater ref="addMater" @refresh="getindex" />

    <imports ref="imports" :table-name="customForm.tableName" :form-info="importForm" @refresh="getindex" />

    <el-drawer title="物资记录" :visible.sync="drawer" :direction="direction">
      <div class="draw">
        <div>种类编码：{{ detailObj.wuzibianma }}</div>
        <div>物资名称：{{ detailObj.zichanmingcheng }}</div>
        <div v-if="detailArr.length>0">
          <el-timeline-item v-for="(item, index) in detailArr" :key="index" :timestamp="item.date">
            <div>
              <p>操作：{{ item.caozuo }}</p>
              <p>人员：{{ item.jingbanren }}</p>
              <p>批次：{{ item.pici }}</p>
              <p>数量：{{ item.shuliang }}</p>
            </div>
          </el-timeline-item>
        </div>
        <div v-else>
          暂无操作记录
        </div>

      </div>
    </el-drawer>

  </div>
</template>

<script>
  import {
    index,
    destroy,
    show
  } from '@/api/system/baseForm.js'
  import addMater from './component/addMater.vue'
  import {
    Message
  } from 'element-ui'
  import imports from '@/views/component/imports.vue'
  import {
    index as fieldIndex
  } from '@/api/system/customFormField'
  import {
    getparameter
  } from '@/api/system/dictionary'
  import * as XLSX from 'xlsx'
  import {
    saveAs
  } from 'file-saver'
  import {
    index as getFenleilist
  } from '@/api/fenlei.js'
  export default {
    components: {
      addMater,
      imports
    },
    data() {
      return {
        loading: false,
        drawer: false,
        direction: 'rtl',
        detailObj: {},
        detailArr: [],
        select: {
          pageSize: 10,
          pageIndex: 1,
          keyword: '',
          fenlei: ''
        },
        fenleiList: [],
        customForm: {
          customFormId: 1,
          tableName: 'material_infos'
        },
        form: [],
        importForm: [],
        total: 0,
        list: [],
        table: [{
            label: '序号',
            type: 'index',
            fixed: 'left',
            width: 80
          },
          {
            label: '物资名称',
            width: 180,
            prop: 'zichanmingcheng',
            align: 'left'
          },
          {
            label: '所属种类',
            width: 180,
            prop: 'fenlei_material_info_types_id_relation.name',
            align: 'center'
          },
          {
            label: '种类编码',
            width: 120,
            prop: 'wuzibianma',
            align: 'center'
          },

          {
            label: '物资类型',
            width: 120,
            prop: 'wuzileixing',
            align: 'center'
          },
          {
            label: '物资型号',
            width: 120,
            prop: 'guigexinghao',
            align: 'left'
          },
          {
            label: '物资规格',
            width: 120,
            prop: 'wuziguige',
            align: 'left'
          },
          {
            label: '单位',
            width: 80,
            prop: 'jiliangdanwei',
            align: 'center'
          },
          {
            label: '储备年限',
            width: 80,
            prop: 'chubeinianxian'
          },
          {
            label: '存放要求',
            width: 120,
            prop: 'cunfangyaoqiu'
          },
          {
            label: '维护要求',
            width: 120,
            prop: 'weihuyaoqiu'
          },
          {
            label: '保养频次',
            width: 120,
            prop: 'equipment_maintain_config_id_equipment_maintain_configs_id_relation.name'
          },
          {
            label: '备注',
            width: 240,
            prop: 'beizhu',
            align: 'left'
          }
        ]
      }
    },
    mounted() {
      this.getFenlei()

      this.getField()
      this.getindex()
    },
    methods: {

      async getFenlei() {
        const res = await getFenleilist({
          tree: 1
        })
        this.fenleiList = this.removeEmptyChildren(res)
      },
      changeFenlei(e, row) {
        console.log('e', e)
        if(e){
          this.select.fenlei = e[e.length - 1]
        }else{
          this.select.fenlei = ''
        }

      },
      // 移除children=[]
      removeEmptyChildren(node) {
        if (Array.isArray(node)) {
          return node.map(child => {
            if (child.children) {
              // 递归处理子节点
              child.children = this.removeEmptyChildren(child.children);
              // 若处理后 children 为空，删除该属性
              if (child.children.length === 0) {
                delete child.children;
              }
            }
            return child;
          });
        }
        return [];
      },
      async getindex() {
        this.loading = true
        const res = await index({
          page_size: this.select.pageSize,
          page: this.select.pageIndex,
          table_name: this.customForm.tableName,
          filter: [{
              'key': 'zichanmingcheng',
              'op': 'like',
              'value': this.select.keyword
            },
            {
              "key": "fenlei",
              "op": "eq",
              "value": this.select.fenlei?this.select.fenlei:''
            },

          ]
        })
        this.list = res.data
        this.total = res.total
        this.loading = false
      },

      pageChange(e) {
        this.select.pageIndex = e
        this.getindex()
      },
      pageSizeChange(e) {
        this.select.pageSize = e
        this.select.pageIndex = 1
        this.getindex()
      },
      editorMater(id, type) {
        this.$refs['addMater'].id = id
        this.$refs['addMater'].type = type
        this.$refs['addMater'].isShow = true
      },
      showMater(id) {
        this.getDetail(id)
      },
      async getDetail(id) {
        const res = await show({
          id: id,
          table_name: this.customForm.tableName
        })
        const _arr = []
        if (res.item_details.length > 0) {
          for (var k of res.item_details) {
            if (k.stocks_id) {
              _arr.push({
                caozuo: '入库',
                jingbanren: k.jingbanren,
                date: k.rukushijian,
                pici: k.rukupici,
                shuliang: k.rukushuliang,
                kucun: k.inventorys_zaikushuliang ? k.inventorys_zaikushuliang : 0
              })
            } else if (k.outbounds_id) {
              _arr.push({
                caozuo: '出库',
                jingbanren: k.jilurenyuan,
                date: k.chukushijian,
                pici: k.rukupici,
                shuliang: k.jieyongshuliang,
                kucun: k.inventorys_zaikushuliang ? k.inventorys_zaikushuliang : 0
              })
            }
          }
        }
        this.detailArr = _arr
        this.detailObj = res
        this.drawer = true
      },
      deleteMater(row) {
        destroy({
          id: row.id,
          table_name: this.customForm.tableName
        }).then(res => {
          Message({
            type: 'success',
            message: '删除成功'
          })
          this.getindex()
        })
      },
      async exportExcel(sheetName) {
        const res = await index(Object.assign(this.select, {
          page: 1,
          page_size: 9999,
          table_name: this.customForm.tableName
        }))
        if (res.data) {
          const headers = this.table.map(i => {
            if (i.type === 'index') {

            } else if (i.prop === 'storages_id_materialstorages_id_relation.cangkumingcheng') {
              return {
                key: 'storages_id',
                title: i.label
              }
            } else {
              return {
                key: i.prop,
                title: i.label
              }
            }
          })
          const data = res.data.map(row => headers.map(header => row[header.key]))
          data.unshift(headers.map(header => header.title))
          const wb = XLSX.utils.book_new()
          const ws = XLSX.utils.aoa_to_sheet(data)
          XLSX.utils.book_append_sheet(wb, ws, sheetName)
          const wbout = XLSX.write(wb, {
            bookType: 'xlsx',
            bookSST: true,
            type: 'array'
          })
          saveAs(new Blob([wbout], {
            type: 'application/octet-stream'
          }), `${sheetName}.xlsx`)
        }
      },
      async getField() {
        const res = await fieldIndex({
          page: 1,
          page_size: 999,
          custom_form_id: this.customForm.customFormId,
          sort_name: 'sort',
          sort_type: 'asc'
        })
        if (res.data && res.data instanceof Array) {
          res.data.forEach(i => {
            if (i.field) {
              if (
                (i.edit_input === 'checkbox' || i.edit_input === 'radio' || i.edit_input === 'select') &&
                i.parameter_id
              ) {
                getparameter({
                  id: i.parameter_id
                }).then((res) => {
                  i._paramters = res.detail ?? []
                })
              }
              if (
                (i.edit_input === 'checkbox' || i.edit_input === 'radio' || i.edit_input === 'select') &&
                i.link_table_name
              ) {
                index({
                  page: 1,
                  page_size: 999,
                  table_name: i.link_table_name
                }).then((res) => {
                  i._paramters = res.data ?? []
                })
              }
            }
          })
        }
        this.form = res.data
        this.importForm = res.data
          ?.filter((i) => i.list_show)
          .map((i) => {
            return i
          })
        this.importForm.unshift({
          filed:'二级分类',
          name:'二级分类'
        })
        this.importForm.unshift({
          filed:'一级分类',
          name:'一级分类'
        })
      }
    }

  }
</script>

<style scoped>
  /deep/ .draw {
    padding-left: 20px;
  }

  /deep/ .draw>div {
    font-size: 20px;
    margin: 15px 0
  }

  /deep/ .el-timeline-item {
    list-style: none;
  }
</style>
