<!--
  @description: 物资列表
  @author: zyy
  @routerPath:
  @date:  2021/3/19 16:04
-->
<template>
  <div>
    <div>
      <table-crud
        ref="tableCrud"
        :search-form="searchForm"
        :menu="true"
        search-label-width="80px"
        :page-flag="true"
        @on-load="loadData"
      >
        <template v-slot:search="search">
          <el-form-item ref="code" label="物资编码" prop="purchaseCode">
            <el-input
              v-model="searchForm.purchaseCode"
              placeholder="请输入"
              style="width:220px"
              @keyup.enter.native="search.onSearch"
            />
          </el-form-item>
          <el-form-item ref="name" label="物资名称" prop="purchaseName">
            <el-input
              v-model="searchForm.purchaseName"
              placeholder="请输入"
              style="width:220px"
              @keyup.enter.native="search.onSearch"
            />
          </el-form-item>
          <el-form-item ref="createUserName" label="创建人" prop="createUserName">
            <el-input
              v-model="searchForm.createUserName"
              placeholder="请输入"
              style="width:220px"
              @keyup.enter.native="search.onSearch"
            />
          </el-form-item>
          <el-form-item label="物资规格" prop="purchaseSpecification">
            <el-input
              v-model="searchForm.purchaseSpecification"
              placeholder="请输入"
              style="width:220px"
              @keyup.enter.native="search.onSearch"
            />
          </el-form-item>
          <el-form-item ref="useStatus" label="作废" prop="useStatus">
            <el-select v-model="searchForm.useStatus">
              <el-option
                v-for="item in useStatusList"
                :key="item.typename"
                :label="item.typename"
                :value="item.typecode"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            ref="createTime"
            label="创建时间"
          >
            <!--创建日期-->
            <el-date-picker
              v-model="searchForm.createTime"
              type="datetimerange"
              range-separator="至"
              unlink-panels
              format="yyyy-MM-dd HH:mm"
              value-format="yyyy-MM-dd HH:mm"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 300px !important;"
              @change="createTimeChange"
            />
          </el-form-item>
        </template>
        <template v-slot:menuLeft>
          <el-button
            type="primary"
            icon="iconfont icon-tianjia1"
            @click="addMaterial"
          >
            新增物资
          </el-button>
          <el-button @click="exportMateriel">
            导出列表
          </el-button>
          <template>
            <el-upload
              ref="upload"
              :action="action"
              :on-success="handleSuccess"
              :on-error="handleError"
              :limit="1"
              :show-file-list="false"
              :headers="importHeaders"
              multiple
              style="display: inline-block;margin-left: 10px;margin-right: 10px;"
            >
              <el-button>导入物资</el-button>
            </el-upload>
            <el-button class="btn-ml10" @click="downloadClick">
              下载模板
            </el-button>
            <!--// 00无效 01 有效-->
            <el-button v-if="useStatus=='01'" class="btn-ml10" @click="dsicard('many')">
              批量作废
            </el-button>
            <el-button v-if="useStatus=='00'" class="btn-ml10" @click="restore(('many'))">
              批量还原
            </el-button>
          </template>
        </template>
        <template v-slot:GXTable>
          <el-table
            ref="smallTable"
            v-loading="loading"
            :data="tableData"
            row-key="id"
            size="small"
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              type="selection"
              width="40"
            />
            <el-table-column
              type="index"
              label="序号"
              fixed
              min-width="75"
              align="center"
            />
            <el-table-column
              prop="purchaseCode"
              fixed
              label="物资编码"
              min-width="100"
            />
            <el-table-column
              header-align="center"
              prop="purchaseName"
              label="物资名称"
              min-width="100"
            />
            <el-table-column
              header-align="center"
              prop="purchaseSpecification"
              label="物资规格型号"
              min-width="110"
            />
            <el-table-column
              label="品牌"
              prop="purchaseBrand"
              min-width="80"
              align="center"
            />
            <el-table-column
              label="计量单位"
              prop="purchaseUnit"
              align="center"
              width="110"
            >
              <template slot-scope="scope">
                <span
                  v-for="(item,index) in purchaseUnitList"
                  v-if="scope.row.purchaseUnit===item.typecode"
                  :key="index"
                >
                  {{ item.typename }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              label="创建人"
              prop="createUserName"
              align="center"
              width="130"
            />
            <el-table-column
              label="创建时间"
              prop="createTime"
              align="center"
              width="130"
            />
            <el-table-column
              header-align="center"
              label="操作"
              fixed="right"
              align="center"
              width="100"
            >
              <template slot-scope="scope">
                <el-link
                  v-if="scope.row.useStatus != '00'"
                  type="primary"
                  @click.stop="editMaterial(scope.row,'edit')"
                >
                  [编辑]
                </el-link>
                <el-link
                  v-if="scope.row.useStatus == '01'"
                  type="primary"
                  @click.stop="dsicard('single',scope.row)"
                >
                  [作废]
                </el-link>
                <el-link
                  v-if="scope.row.useStatus == '00'"
                  type="primary"
                  @click.stop="restore('single',scope.row)"
                >
                  [还原]
                </el-link>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </table-crud>
      <!--新增/编辑物资弹框-->
      <add-material
        v-if="dialogData.consignContractVisible"
        :dialog-data="dialogData"
        :planmainid="searchForm.planMainId"
        @onClose="onClose"
      />
    </div>
  </div>
</template>
<script>
/* api */
import { ListTBMaterialStoreInfo } from '@/api/procurement/purchasplan' // 查询物资信息列表
import {
  deleteProtPlanMaterialStoreById, // 删除物料信息
  changeUseStatusProtPlanMaterialStoreById, // 还原
  downloadProtPlanMaterialStoreInfoTemplate, // 导出模板
  exportExcelprotPlanMaterialStoreInfoList, // 导出物料信息列表
  importExcelProtPlanMaterialStoreInfo // 导入
} from '@/api/procurement/purchasplan'
import { download } from '@/assets/js/utils/index' // 文件回显组件
/* 混入 */
import { ListMixin } from '@/mixins/ListMixin' // 分页
import { procurementPlanGrounpMixins } from '@/views/procurement/procurementPlan/mixins/procurementPlanGroupMixins' // 字典
/* 组件 */
import addMaterialDialog from '../materialStore/materialAdd-dialog' // 新增/编辑弹窗
import Cookies from 'js-cookie'
export default {
  name: 'MaterialChildrenList',
  components: {
    'add-material': addMaterialDialog // 新增/编辑物资
  },
  mixins: [ListMixin, procurementPlanGrounpMixins],
  props: {
    materialType: {
      type: Object,
      default: function() {
        return {
          smallCode: '', // 物资小类编码
          smallName: '' // 物资小类名称
        }
      }
    }
  },
  data() {
    return {
      loading: false, // loading
      action: importExcelProtPlanMaterialStoreInfo, // 模板导入接口
      importHeaders: {}, // 用户信息
      fileUrl: '', // 模板路径
      useStatus: '01', // 当前页面数据状态
      checkedUseStatusList: [], // 复选框选中
      // 00无效 01 有效
      useStatusList: [
        {
          typecode: '01',
          typename: '否'
        },
        {
          typecode: '00',
          typename: '是'
        }
      ],
      searchForm: {
        purchaseCode: '', // 物资编码
        purchaseName: '', // 物资名称
        purchaseSpecification: '',
        createTime: [], // 创建时间
        createUserName: '', // 创建人
        createStartTime: '', // 创建开始时间
        createEndTime: '', // 创建结束时间
        useStatus: '01' // 状态
        // smallCode: '' // 物资小类编码
      },
      tableData: [],
      // 添加/编辑弹窗-展示/隐藏状态 true 展示/false 隐藏
      dialogData: {
        consignContractVisible: false,
        smallCode: '', // 物资小类编码
        smallName: '', // 物资小类名称
        handleType: '', // 操作类型，add 新增，edit 编辑
        id: '' // 物资类ID
      }
    }
  },
  watch: {
    materialType(res) {
      this.dialogData.smallCode = res.smallCode
      this.dialogData.smallName = res.smallName
      this.$refs.tableCrud.onSearchChange() // 查询按钮数据
    }
  },
  created() {
    this.importHeaders['X-AUTH-TOKEN'] = Cookies.get('X-AUTH-TOKEN') // 拿到token
  },
  methods: {
    // 创建时间选择
    createTimeChange(val) {
      this.searchForm.createStartTime = val[0]// 开始日期
      this.searchForm.createEndTime = val[1]// 结束日期
    },
    // 模板导入成功后的回调
    handleSuccess(response, file, fileList) {
      // 模板导入成功后
      if (response.header.ret === '0') {
        this.$message.success(response.header.msg)
        //  清空
        this.$refs.upload.clearFiles()
        this.$refs.tableCrud.onSearchChange() // 查询按钮数据
        return
      }
      // 上传失败
      this.$refs.upload.clearFiles()
      this.$message.warning(response.header.msg)
    },
    // 模板导入失败后的回调
    handleError(response, file, fileList) {
      this.$message.error(response.header.msg)
      this.$refs.upload.clearFiles()
      this.$message.error(response.header.msg)
      this.$refs.tableCrud.onSearchChange() // 查询按钮数据
    },
    // 下载计划详情模板
    downloadClick() {
      downloadProtPlanMaterialStoreInfoTemplate().then(res => {
        download(res, '物料信息导入模板.xlsx')
      })
    },
    // 录入弹框关闭
    onClose() {
      this.$refs.tableCrud.onSearchChange() // 查询按钮数据
    },
    // 添加物资
    addMaterial() {
      if (this.materialType.categoryIsLeaf !== '1') {
        this.$message.warning('只能在物料分类最底层节点下新增物料')
        return
      }
      // 开启弹框
      this.dialogData.handleType = 'add'
      this.dialogData.consignContractVisible = true
    },
    // 导出物资
    exportMateriel() {
      const data = {
        smallCode: this.materialType.smallCode, // 小类编码
        purchaseCode: this.searchForm.purchaseCode, // 物资编码
        purchaseName: this.searchForm.purchaseName, // 物资名称
        createUserName: this.searchForm.purchaseName, // 创建人
        createStartTime: this.searchForm.createStartTime, // 创建开始时间
        createEndTime: this.searchForm.createEndTime, // 创建结束时间
        useStatus: this.searchForm.useStatus // 状态
      }
      exportExcelprotPlanMaterialStoreInfoList(data).then(res => {
        download(res, '物料信息.xlsx')
      })
    },
    /*
    * 打开新增按钮/编辑按钮弹框
    * @params row: 按钮行信息  type: add ||rowAdd 新增 edit 编辑
    */
    editMaterial(row, type) {
      this.dialogData.handleType = 'edit' // 编辑操作
      this.dialogData.id = row.itemId // 物资类ID
      this.dialogData.purchaseUnit = row.purchaseUnit // 计量单位
      this.dialogData.purchaseCode = row.purchaseCode // 物资编码
      this.dialogData.purchaseName = row.purchaseName // 物料名称
      this.dialogData.purchaseSpecification = row.purchaseSpecification // 物资规格/规格型号
      this.dialogData.purchaseBrand = row.purchaseBrand // 品牌
      this.dialogData.consignContractVisible = true // 弹框状态
    },
    /*
    * 删除事件
    * @params row: 按钮行信息
    */
    deleteMaterial(row, index) {
      this.$confirm('确认要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonClass: 'confirmBtn',
        cancelButtonClass: 'cancelBtn',
        type: 'warning'
      }).then(() => {
        const data = {
          materialStoreId: row.itemId // 按钮主键id
        }
        // 删除方法
        deleteProtPlanMaterialStoreById(data).then(() => {
          this.$message.success({ message: '删除成功' })
          this.$refs.tableCrud.onSearchChange() // 查询按钮数据
        })
      })
    },
    // 获取数据
    loadData(params, callback) {
      // 组装物资分类参数
      const data = { ...params, smallCode: this.materialType.smallCode }
      delete data.createTime
      ListTBMaterialStoreInfo(data).then(response => {
        this.loading = false
        this.tableData = response.data.records
        if (this.tableData && this.tableData.length > 0) {
          this.useStatus = this.tableData[0].useStatus
        }
        callback(response.data.total)
      }).catch(() => {
        this.loading = false
      })
    },
    // 复选框
    handleSelectionChange(val) {
      this.checkedUseStatusList = val
    },
    // dsicard 废弃物料
    dsicard(type, param) {
      let materialStoreIds = []
      if (type && type === 'single') {
        // 操作单个
        materialStoreIds.push(param.itemId)
      } else {
        // 操作多个
        if (this.checkedUseStatusList && this.checkedUseStatusList.length > 0) {
          materialStoreIds = this.checkedUseStatusList.map((val) => {
            return val.itemId
          })
        } else {
          this.$message.warning('请选择要作废的物料')
          return
        }
      }
      this.$confirm('确认要作废吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonClass: 'confirmBtn',
        cancelButtonClass: 'cancelBtn',
        type: 'warning'
      }).then(() => {
        // const data = {
        //   materialStoreIds: materialStoreIds // 按钮主键id
        // }
        // 废弃方法
        deleteProtPlanMaterialStoreById(materialStoreIds).then(() => {
          this.$message.success({ message: '操作成功' })
          this.$refs.tableCrud.onSearchChange() // 查询按钮数据
        })
      })
    },
    // restore 还原物料
    restore(type, param) {
      let materialStoreIds = []
      if (type && type === 'single') {
        // 操作单个
        materialStoreIds.push(param.itemId)
      } else {
        // 操作多个
        if (this.checkedUseStatusList && this.checkedUseStatusList.length > 0) {
          materialStoreIds = this.checkedUseStatusList.map((val) => {
            return val.itemId
          })
        } else {
          this.$message.warning('请选择要还原的物料')
          return
        }
      }
      this.$confirm('确认要还原吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonClass: 'confirmBtn',
        cancelButtonClass: 'cancelBtn',
        type: 'warning'
      }).then(() => {
        // const data = {
        //   materialStoreIds: materialStoreIds // 按钮主键id
        // }
        // 还原方法
        changeUseStatusProtPlanMaterialStoreById(materialStoreIds).then(() => {
          this.$message.success({ message: '操作成功' })
          this.$refs.tableCrud.onSearchChange() // 查询按钮数据
        })
      })
    }
  }
}
</script>
<style lang="less" scoped>
  /deep/.title_border{
    display: none;
  }
</style>
