<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;">
            <Input v-model="select.keyword" style="width: 200px;margin-right: 10px;" placeholder="关键词搜索" />
            <Select v-model="select.suozaicangku" style="width: 200px;margin-right: 10px;" placeholder="所在仓库" clearable>
              <Option v-for="item in cangkuList" :key="item.id" :value="item.cangkumingcheng">{{ item.cangkumingcheng }}</Option>
            </Select>
            <Button type="primary" @click="getindex">查询</Button>
            <Button icon="ios-add" type="primary" style="margin-left: 10px;"
              @click="$refs['addMater'].isShow = true,$refs['addMater'].type = 'add'">添加</Button>
            <Button icon="ios-add" type="primary" style="margin-left: 10px;"
              @click="$refs['imports'].show()">导入</Button>
              <Button type="primary" style="margin-left: 10px;"
                @click="exportExcel(new Date().getTime().toString())">导出</Button>
          </div>
        </slot>
      </lx-header>
    </div>

    <xy-table :list="list" :total="total" v-loading="loading" @pageSizeChange="e => select.pageSize = e"
      @pageIndexChange="pageChange" :table-item="table">
      <template v-slot:btns>
        <el-table-column fixed="right" label="操作" width="260" 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>
              <!-- <Button type="primary" size="small" @click="editorMater(scope.row.id,'editor')">请示流程</Button> -->
              <!-- <Button type="primary" size="small" @click="editorActivity(scope.row.id,'editor')">编辑</Button>
               <Button style="margin-left: 10px;" type="primary" size="small" @click="checkActivity(scope.row.id)">审核</Button>
              <Button type="primary" size="small" style="margin-left: 10px;" @click="editorActivity(scope.row.id,'copy')">复制新增</Button> -->
              <Poptip transfer confirm title="确认要删除吗？" @on-ok="deleteMater(scope.row)">
                <Button type="primary" style="margin-left: 10px;" size="small" ghost>删除</Button>
              </Poptip>
            </div>

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

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

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

    <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>
                <!-- <p>库存：{{item.kucun}}</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 {
    getInfo
  } from "@/api/user.js"
  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";
  export default {
    components: {
      addMater,
      imports
    },
    data() {
      return {
        authName: '',
        roleName: '',
        loading: false,
        drawer: false,
        direction: 'rtl',
        detailObj: {},
        detailArr: [],
        select: {
          pageSize: 10,
          pageIndex: 1,
          keyword: "",
          suozaicangku:''
        },
        cangkuList:[],
        customForm: {
          customFormId: 1,
          tableName: "material_infos"
        },
        form: [],
        importForm: [],
        total: 0,
        list: [],
        table: [{
            label: '序号',
            type: 'index',
            fixed: 'left',
            width: 80
          },
          {
            label: "物资编码",
            width: 120,
            prop: 'wuzibianma',
            align: 'center',
          },
          {
            label: "资产名称",
            width: 180,
            prop: 'zichanmingcheng',
            align: 'left'
          },
          {
            label: "物资类型",
            width: 180,
            prop: 'wuzileixing',
            align: 'center'
          },
          {
            label: "规格型号",
            width: 180,
            prop: 'guigexinghao',
            align: 'left'
          },
          {
            label: "分类",
            width: 180,
            prop: 'fenlei',
            align: 'center'
          },
          // {
          //   label: "状态",
          //   width: 180,
          //   prop: 'zhuangtai',
          //   align: 'center'
          // },
          {
            label: "计量单位",
            width: 180,
            prop: 'jiliangdanwei',
            align: 'center'
          },
          {
            label: "所在仓库",
            width: 180,
            prop: 'materialstorages_details.cangkumingcheng',
            align: 'center'
          },
          // {
          //   label: "所在货架",
          //   width: 180,
          //   prop: 'suozaihuojia',
          //   align: 'center'
          // },
          {
            label: "入库时间",
            width: 180,
            prop: 'rukushijian',
            align: 'center'
          },
          // {
          //   label: "资产原值",
          //   width: 180,
          //   prop: 'zichanyuanzhi',
          //   align: 'center'
          // },
          {
            label: "使用年限",
            width: 180,
            prop: 'shiyongnianxian',
            align: 'center'
          },
          // {
          //   label: "使用部门",
          //   width: 180,
          //   prop: 'shiyongbumen',
          //   align: 'center'
          // },
          {
            label: "是否为固定资产",
            width: 180,
            prop: 'shifouweigudingzichan',
            align: 'center'
          },
          {
            label: "库存",
            width: 180,
            prop: 'inventorys_total',
            align: 'center'
          },
          {
            label: "备注",
            width: 240,
            prop: 'beizhu',
            align: 'left'
          }
        ]
      }
    },
    mounted() {
      this.getCangku()
      this.getField()
      this.getindex()
    },
    methods: {
      async getCangku() {
        let res = await index({
          page_size: 999,
          page: 1,
          table_name: 'materialstorages',
        })
        this.cangkuList = res.data
      },
      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": "suozaicangku",
            "op": "eq",
            "value": this.select.suozaicangku?this.select.suozaicangku:''
          },

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

      pageChange(e) {
        this.select.pageIndex = e
        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
        })
        let _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) {
          let headers = this.importForm.map(i => {
            return {
              key: i.field,
              title: i.name
            }
          })
          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
          })
      },
    },

  }
</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>
