<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="部门" prop="deptId" v-show="deptShow">
        <el-select v-model="queryParams.deptId" filterable placeholder="请选择部门"   clearable>
          <el-option
            v-for="dict in allDeptList"
            :key="dict.deptId"
            :label="dict.deptName"
            :value="dict.deptId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="物资分类" prop="classFirst"   >
        <el-select v-model="queryParams.classFirst"  @change="classFirstChange" placeholder="请选择标签" clearable>
          <el-option
            v-for="dict in dict.type.material_class_fast"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="性质"   prop="materialType">
        <el-select v-model="queryParams.materialType" placeholder="请选择性质" clearable>
          <el-option
            v-for="dict in materialTypeOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item
      >
      <el-form-item label="物资名称"   prop="classSecond">
        <el-cascader style="width:500px"
                     v-model="queryParams.materialNameId"
                     :options="options"
                     :props="{ multiple: false, checkStrictly: true }"
                     @change="handleQueryChange"></el-cascader>
      </el-form-item>
<!--      <el-form-item label="类别"   prop="classSecond">

        <el-cascader style="width:500px"
                     v-model="queryParams.materialNameId"
                     :options="options"
                     :props="{ multiple: false, checkStrictly: true }"
                     @change="handleQueryChange"></el-cascader>
      </el-form-item>-->

<!--      <el-form-item label="物资名称" prop="materialName">
        <el-input
          v-model="queryParams.materialName"
          placeholder="请输入物资名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>-->






      <!--<el-form-item label="规格/参数" prop="materialSpecs">
        <el-input
          v-model="queryParams.materialSpecs"
          placeholder="请输入规格/参数"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="数量" prop="materialQuantity">
        <el-input
          v-model="queryParams.materialQuantity"
          placeholder="请输入数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="储备地点" prop="reserveLocation">
        <el-input
          v-model="queryParams.reserveLocation"
          placeholder="请输入储备地点"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="管理责任人" prop="managerPerson">
        <el-input
          v-model="queryParams.managerPerson"
          placeholder="请输入管理责任人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="tel">
        <el-input
          v-model="queryParams.tel"
          placeholder="请输入联系电话"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ehsMaterial:ehsMaterial:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ehsMaterialList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="上报部门" align="center" prop="deptName" />
     <!-- <el-table-column label="主键" align="center" prop="materialId" />-->
      <el-table-column label="性质" align="center" prop="materialType">
        <template slot-scope="scope">
          <span> {{ materialTypeOptions[scope.row.materialType-1].label}}</span>
        </template>
      </el-table-column>
      <el-table-column label="分类" align="center" prop="classFirst">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.material_class_fast" :value="scope.row.classFirst"/>
        </template>
      </el-table-column>
      <el-table-column label="类别" align="center" prop="classSecond">
        <template slot-scope="scope">
          <span>{{classToStr(scope.row.classSecond,1)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="物资名称" align="center" prop="materialName" >
      <template slot-scope="scope">
        <span>{{classToStr(scope.row.materialName,2)}}</span>
      </template>
      </el-table-column>
      <el-table-column label="规格/参数" align="center" prop="materialSpecs" />
      <el-table-column label="数量" align="center" prop="materialQuantity" />
      <el-table-column label="待处理出库" align="center" prop="sendQuantity" />
      <el-table-column label="储备地点" align="center" prop="reserveLocation" />
      <el-table-column label="管理责任人" align="center" prop="managerPerson" />
      <el-table-column label="联系电话" align="center" prop="tel" />
      <el-table-column label="更新时间" align="center" prop="updateTime"  >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">

          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDetail(scope.row)"
            v-hasPermi="['EhsMaterialDetail:EhsMaterialDetail:list']"
          >出入库明细</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="titleDetail" :visible.sync="openDetail" width="800px" append-to-body>
      <el-table v-loading="loading" :data="ehsMaterialDetailList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
<!--        <el-table-column label="主键" align="center" prop="materialDetailId" />
        <el-table-column label="物资表" align="center" prop="materialId" />-->
        <el-table-column label="出库指令发送人" align="center" prop="sendUserName" />
        <el-table-column label="出库指令数量" align="center" prop="sendQuantity" />
        <el-table-column label="出库指令发送时间" align="center" prop="sendTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.sendTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="出/入库类型" align="center" prop="sendTime" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.operateType==0?"出库":"入库" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="出/入库人" align="center" prop="outboundUserName" />
        <el-table-column label="出/入库数量" align="center" prop="outboundQuantity" />
        <el-table-column label="当前库存" align="center" prop="inventory" />
        <el-table-column label="操作时间" align="center" prop="outboundTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.outboundTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>

      </el-table>
      <pagination
        v-show="total>0"
        :total="totalDetail"
        :page.sync="pageNum"
        :limit.sync="pageSize"
        @pagination="getListDetail"
      />

    </el-dialog>
  </div>
</template>

<script>
  import { listEhsMaterial, getEhsMaterial, delEhsMaterial, addEhsMaterial, updateEhsMaterial } from "@/api/ehs/ehsMaterial";
  import {listAllDept } from "@/api/system/dept";
  import {addEhsMaterialDetail,listEhsMaterialDetail, updateEhsMaterialDetail , delEhsMaterialDetail} from "@/api/ehs/EhsMaterialDetail";
  import material1 from '../../../assets/materialClass.json';
  import material2 from '../../../assets/materialClass2.json';
  import material3 from '../../../assets/materialClass3.json';
  import material4 from '../../../assets/materialClass4.json';
  import material5 from '../../../assets/materialClass5.json';
  import material6 from '../../../assets/materialClass6.json';
  import material7 from '../../../assets/materialClass7.json';
  import material8 from '../../../assets/materialClass8.json';
  export default {
    name: "EhsMaterial",
    dicts: ['material_class_fast' ],
    data() {
      return {
        options:material1,
        curDict:[],
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 物资信息包含  通用应急救援装备”“防汛抗旱应急救援装备”“森林防灭火应急救援装备”“救灾物资”表格数据
        ehsMaterialList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        titleDetail: "出入库明细",
        // 是否显示弹出层
        openDetail: false,
        ehsMaterialDetailList:[],
        totalDetail: 0,
        materialClass:0,
        materialDetailId:null,
        // 弹框分页
        total1:2,
        pageNum: 1,
        pageSize: 10,
        //是否显示部门列表查询条件
        deptShow: false,
        //所有部门列表字典
        allDeptList: [],
        sendQuantity:"",//发送的指令
        materialTypeOptions: [{
          value: 1,
          label: '自储',
          raw:{listClass: 'default'}
        }, {
          value: 2,
          label: '社会代储',
          raw:{listClass: 'default'}
        }],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          materialType: null,
          classSecond: null,
          materialName: null,
          materialSpecs: null,
          materialQuantity: null,
          reserveLocation: null,
          managerPerson: null,
          tel: null,
          classFirst:null
        },
      };
    },
    created() {
      this.getList();
      this.materialClass = this.$route.query.classFirst;
      this.getListAllDept();
      this.deptShow = this.$store.state.user.parentId==0 ?true :false;

    },

    methods: {
      /** 查询物资信息包含  通用应急救援装备”“防汛抗旱应急救援装备”“森林防灭火应急救援装备”“救灾物资”列表 */
      getList() {
        this.loading = true;
        listEhsMaterial(this.queryParams).then(response => {
          this.ehsMaterialList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      /** 单位信息列表 */
      getListAllDept() {
        console.log(this.$store.state.user.deptId);
        this.loading = true;
        listAllDept().then(response => {
          this.allDeptList = response.data;
          this.loading = false;
        });
      },

      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          materialId: null,
          materialType: null,
          classFirst: null,
          classSecond: null,
          materialName: null,
          materialSpecs: null,
          materialQuantity: null,
          reserveLocation: null,
          managerPerson: null,
          tel: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null,
          deptId: null,
          createUserId: null,
          updateUserId: null,
          classFirst:this.$route.query.classFirst
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.queryParams.materialNameId = null;
        this.queryParams.materialName = null;
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.materialId)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加物资信息包含";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const materialId = row.materialId || this.ids
        getEhsMaterial(materialId).then(response => {
          this.form = response.data;
          this.form.materialNameId = [];
          this.form.materialNameId.push(this.form.classSecond);
          this.form.materialNameId.push(this.form.materialName);
          console.log(this.form.materialNameId);
          this.open = true;
          this.title = "修改物资信息";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.form.classSecond = this.form.materialNameId[0];
            this.form.materialName = this.form.materialNameId[1];
            if (this.form.materialId != null) {
              updateEhsMaterial(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addEhsMaterial(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const materialIds = row.materialId || this.ids;
        this.$modal.confirm('是否确认删除物资信息' + materialIds + '"的数据项？').then(function() {
          return delEhsMaterial(materialIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('ehsMaterial/ehsMaterial/export', {
          ...this.queryParams
        }, `ehsMaterial_${new Date().getTime()}.xlsx`)
      },
      handleSendCommand(row) {
        if(row.sendQuantity!=null){
          this.$message.error('此物资已有待处理出库，无法重复发送出库指令！');
          return;
        }
        this.$prompt('请输入出库数量', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^\d+$|^\d+[.]?\d+$/,
          inputErrorMessage: '出库数量只能是数字'
        }).then(({ value }) => {
          this.loading = true;
            //this.sendQuantity = value;
            addEhsMaterialDetail({"sendQuantity":value,"materialId":row.materialId,"operateType":0}).then(response => {
            this.$modal.msgSuccess("出库指令发送成功");
            this.loading = false;
            this.getList();
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          });
        });
      },
      getListDetail() {
        this.loading = true;
        listEhsMaterialDetail({"pageNum" : this.pageNum, "pageSize": this.pageSize,"materialId":this.materialDetailId}).then(response => {
          this.ehsMaterialDetailList = response.rows;
          this.totalDetail = response.total;
          this.loading = false;
        });
      },
      handleDetail(row) {
        this.openDetail=true;
        this.materialDetailId = row.materialId;
        this.getListDetail();
      },/**  */
      handleOutbound(row) {
        this.$modal.confirm('是否执行出库指令？' ).then(function() {
          return updateEhsMaterialDetail({"materialId":row.materialId});
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("执行成功");
        }).catch(() => {});
      },
      /** 入库 */
      handleInbound(row) {
        this.$prompt('请输入入库数量', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^\d+$|^\d+[.]?\d+$/,
          inputErrorMessage: '入库数量只能是数字'
        }).then(({ value }) => {
          this.loading = true;
          //this.sendQuantity = value;
          addEhsMaterialDetail({"outboundQuantity":value,"materialId":row.materialId,"operateType":1}).then(response => {
            this.$modal.msgSuccess("入库成功");
            this.loading = false;
            this.getList();
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          });
        });
      },
      handleDelDetail(row) {
        this.$modal.confirm('是否终止出库指令？' ).then(function() {
          return delEhsMaterialDetail(row.materialId);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("终止成功");
        }).catch(() => {});
      },
      handleChange(value) {
        console.log(value);
      },
      handleQueryChange(value) {
        if(value.length==2){
          this.queryParams.classSecond = value[0]   ;
          this.queryParams.materialName = value[1]   ;
        }else if(value.length==1){
          this.queryParams.classSecond = value[0]   ;
        }
      },
      classToStr(value,type) {
        let str ="";
        if(type==1){
          this.options.forEach(item =>{
            if(item.value==value){
              str = item.label;
              }
            })
        }else{
          this.options.forEach(item =>{
            let v = value.split("-");
            if(item.value==v[0]){
              item.children.forEach(it =>{
                if(it.value==value){
                  str =  it.label;
                }
              })
            }
          })
        }
        console.log(str);
        return str;
      },
      classFirstChange(value){
        if (value == 1){
          this.options = material1;
        }else if (value == 2){
          this.options = material2;
        }else if (value == 3){
          this.options = material3;
        }else if (value == 4){
          this.options = material4;
        }else if (value == 5){
          this.options = material5;
        }else if (value == 6){
          this.options = material6;
        }else if (value == 7){
          this.options = material7;
        }else if (value == 8){
          this.options = material8;
        }

      }
    }
  };
</script>
