<template>
  <div class="app-container">
    <div class="query-container">
      <el-form :model="queryParams" ref="queryForm" size="mini" :inline="true">
        <el-form-item prop="materialName">
          <el-input
            v-model="queryParams.materialName"
            placeholder="请输入物料名称"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="只看自己" prop="self">
          <el-switch v-model="queryParams.self"></el-switch>
        </el-form-item>
        <el-form-item prop="monthOrWeek">
          <el-radio-group v-model="queryParams.monthOrWeek" @change="radioChange">
            <el-radio-button label="1">月</el-radio-button>
            <el-radio-button label="2">周</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="recordDate">
          <div v-if="queryParams.monthOrWeek==='1'">
            <el-date-picker
              v-model="queryParams.date"
              type="month"
              value-format="yyyy-MM"
              placeholder="选择月份"
              @change="handleQuery"
              clearable>
            </el-date-picker>
          </div>
          <div v-if="queryParams.monthOrWeek==='2'">
            <el-date-picker
              v-model="queryParams.date"
              type="week"
              format="yyyy 第 WW 周"
              placeholder="选择周"
              @change="handleQuery"
              clearable>
            </el-date-picker>
          </div>
        </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" style="margin-bottom: 8px">
        <el-col :span="1.5" v-if="queryParams.monthOrWeek==='1'">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['material:receive:add']"
          >新增
          </el-button>
        </el-col>
        <el-col :span="1.5" v-if="queryParams.monthOrWeek==='1'">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            :disabled="addList.length===0"
            @click="handleSplit"
            v-hasPermi="['material:receive:add']"
          >周数据
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['material:receive:export']"
          >导出
          </el-button>
        </el-col>
      </el-row>
    </div>

    <el-table :data="materialList"
              ref="materialList"
              stripe
              height="calc(100vh - 180px)"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" :selectable="selectableHandler"
                       v-if="queryParams.monthOrWeek==='1'"/>
      <el-table-column label="编号" prop="id" width="80"/>
      <el-table-column label="物料名称" prop="materialName" :show-overflow-tooltip="true"/>
      <el-table-column label="规格" prop="specification" :show-overflow-tooltip="true"/>
      <el-table-column label="品牌/货号" prop="articleNo" :show-overflow-tooltip="true"/>
      <el-table-column label="厂商" prop="factory"/>
      <el-table-column label="领取量" prop="num" mini-width="80"/>
      <el-table-column label="单位" prop="unit" mini-width="80"/>
      <el-table-column label="物料类型" mini-width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.materialType==='1'" type="warning" size="mini">生产</el-tag>
          <el-tag v-else type="info" size="mini">非生产</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="领用人" prop="receiveUserName" width="100"/>
      <el-table-column label="周期" prop="recordDate" :width="queryParams.monthOrWeek==='1'?100:160"/>
      <el-table-column label="操作" align="center" width="130">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="showEditBtn(scope.row)"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['material:receive:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['material:receive:delete']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 10px;text-align: center">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 50]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>


    <!-- 添加物料配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" @close="dialogClose" width="80%" append-to-body
               :close-on-click-modal="false">
      <el-form ref="addForm" :model="addForm" :rules="rules" size="mini" inline>
        <el-row>
          <el-col :span="22">
            <el-form-item label="数据周期" prop="date">
              <div v-if="addForm.monthOrWeek==='1'">
                <el-date-picker
                  v-model="addForm.date"
                  type="month"
                  value-format="yyyy-MM"
                  placeholder="选择月份"
                  :picker-options="getPickerOptions('month')"
                  clearable>
                </el-date-picker>
              </div>
              <div v-else>
                <el-date-picker
                  v-model="addForm.date"
                  type="week"
                  format="yyyy 第 WW 周"
                  placeholder="选择周"
                  :picker-options="getPickerOptions('week')"
                  clearable>
                </el-date-picker>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item>
              <el-button icon="el-icon-plus" @click="addRow">添加</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table :data="addList" class="add-table" border size="mini">
        <el-table-column label="物料名称" prop="materialName">
          <template slot="header" slot-scope="scope">
            <span style="color: red">*</span><span>物料名称</span>
          </template>
          <template slot-scope="scope">
            <el-input v-model="scope.row.materialName" size="mini" placeholder="请输入物料名称"
                      :disabled="addForm.monthOrWeek==='2'"/>
          </template>
        </el-table-column>
        <el-table-column label="规格" prop="specification">
          <template slot="header" slot-scope="scope">
            <span style="color: red">*</span><span>规格</span>
          </template>
          <template slot-scope="scope">
            <el-input v-model="scope.row.specification" size="mini" placeholder="请输入物料规格"
                      :disabled="addForm.monthOrWeek==='2'"/>
          </template>
        </el-table-column>
        <el-table-column label="品牌/货号" prop="articleNo">
          <template slot="header" slot-scope="scope">
            <span style="color: red">*</span><span>品牌/货号</span>
          </template>
          <template slot-scope="scope">
            <el-input v-model="scope.row.articleNo" size="mini" placeholder="请输入品牌/货号"
                      :disabled="addForm.monthOrWeek==='2'"/>
          </template>
        </el-table-column>
        <el-table-column label="厂商" prop="factory">
          <template slot="header" slot-scope="scope">
            <span style="color: red">*</span><span>厂商</span>
          </template>
          <template slot-scope="scope">
            <el-input v-model="scope.row.factory" size="mini" placeholder="请输入厂商"
                      :disabled="addForm.monthOrWeek==='2'"/>
          </template>
        </el-table-column>
        <el-table-column label="单位" prop="unit" width="120px">
          <template slot="header" slot-scope="scope">
            <span style="color: red">*</span><span>单位</span>
          </template>
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.unit"
              filterable
              allow-create
              default-first-option
              :disabled="addForm.monthOrWeek==='2'"
              style="width: 100%">
              <el-option v-for="item in unitOptions"
                         :key="item"
                         :label="item"
                         :value="item">
              </el-option>
            </el-select>
            <!--            <el-input v-model="scope.row.unit" size="mini" placeholder="请输入单位" :disabled="addForm.monthOrWeek==='2'"-->
            <!--                      style="width: 100%"/>-->
          </template>
        </el-table-column>
        <el-table-column label="价格" prop="price" width="120px">
          <template slot="header" slot-scope="scope">
            <span style="color: red">*</span><span>价格</span>
          </template>
          <template slot-scope="scope">
            <el-input v-model="scope.row.price" size="mini" placeholder="请输入单价" :disabled="addForm.monthOrWeek==='2'"
                      style="width: 100%"/>
          </template>
        </el-table-column>
        <el-table-column label="领取量" prop="num" width="100px">
          <template slot="header" slot-scope="scope">
            <span style="color: red">*</span><span>领取量</span>
          </template>
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.num" size="mini" controls-position="right" :min="0"
                             placeholder="请输入领取量" style="width: 100%"/>
          </template>
        </el-table-column>
        <el-table-column label="物料类型" prop="materialType" width="100px">
          <template slot="header" slot-scope="scope">
            <span style="color: red">*</span><span>物料类型</span>
          </template>
          <template slot-scope="scope">
            <el-select v-model="scope.row.materialType" size="mini" :disabled="addForm.monthOrWeek==='2'"
                       style="width: 100%">
              <el-option label="生产" value="1"></el-option>
              <el-option label="非生产" value="2"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="用于项目" prop="projectId" width="120px">
          <template slot-scope="scope">
            <el-select v-model="scope.row.projectId" size="mini" :disabled="addForm.monthOrWeek==='2'"
                       style="width: 100%">
              <el-option v-for="(item,index) in projectList" :label="item.projectName" :key="index"
                         :value="item.id"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="备注">
          <template slot-scope="scope">
            <el-input v-model="scope.row.remark" size="mini" type="textarea" autosize/>
          </template>
        </el-table-column>
        <el-table-column width="50">
          <template slot-scope="scope">
            <el-button
              size="mini"
              icon="el-icon-delete"
              @click="deleteRow(scope.row)">
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" size="mini">确 定</el-button>
        <el-button @click="cancel" size="mini">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改物料配置对话框 -->
    <el-dialog title="修改" :visible.sync="editOpen" @close="dialogClose" width="500px" append-to-body
               :close-on-click-modal="false">
      <el-form ref="editForm" :model="editForm" :rules="rules" size="mini" label-width="100px">
        <el-form-item label="数据周期" prop="date">
          <div v-if="editForm.monthOrWeek==='1'">
            <el-date-picker
              v-model="editForm.date"
              type="month"
              value-format="yyyy-MM"
              placeholder="选择月份"
              :picker-options="getPickerOptions('month')"
              clearable>
            </el-date-picker>
          </div>
          <div v-else>
            <el-date-picker
              v-model="editForm.date"
              type="week"
              format="yyyy 第 WW 周"
              placeholder="选择周"
              :picker-options="getPickerOptions('week')"
              clearable>
            </el-date-picker>
          </div>
        </el-form-item>
        <el-form-item label="物料名称" prop="materialName">
          <el-input v-model="editForm.materialName" placeholder="请输入物料名称" :disabled="editForm.monthOrWeek==='2'"/>
        </el-form-item>
        <el-form-item label="物料规格" prop="specification">
          <el-input v-model="editForm.specification" placeholder="请输入物料规格" :disabled="editForm.monthOrWeek==='2'"/>
        </el-form-item>
        <el-form-item label="品牌/货号" prop="articleNo">
          <el-input v-model="editForm.articleNo" placeholder="请输入品牌/货号" :disabled="editForm.monthOrWeek==='2'"/>
        </el-form-item>
        <el-form-item label="厂商" prop="factory">
          <el-input v-model="editForm.factory" placeholder="请输入厂商" :disabled="editForm.monthOrWeek==='2'"/>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-select
            v-model="editForm.unit"
            filterable
            allow-create
            default-first-option
            :disabled="editForm.monthOrWeek==='2'"
            style="width: 100%">
            <el-option v-for="item in unitOptions"
                       :key="item"
                       :label="item"
                       :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="editForm.price" placeholder="请输入价格" :disabled="editForm.monthOrWeek==='2'"/>
        </el-form-item>
        <el-form-item label="领取量" prop="num">
          <el-input-number v-model="editForm.num" controls-position="right" :min="0" placeholder="请输入领取量"/>
        </el-form-item>
        <el-form-item label="物料类型" prop="materialType">
          <el-radio-group v-model="editForm.materialType" :disabled="editForm.monthOrWeek==='2'">
            <el-radio label="1">生产</el-radio>
            <el-radio label="2">非生产</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="用于项目" prop="projectId">
          <el-select v-model="editForm.projectId" size="mini" :disabled="editForm.monthOrWeek==='2'"
                     style="width: 100%">
            <el-option v-for="(item,index) in projectList" :label="item.projectName" :key="index"
                       :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="editForm.remark" type="textarea"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="submitEditForm">确 定</el-button>
        <el-button size="mini" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listMaterial,
  getMaterial,
  delMaterial,
  addMaterial,
  updateMaterial,
  exportMaterial
} from "@/api/material/material";
import {listProject} from "@/api/task/project";
import DateUtil from "@/utils/date"

export default {
  name: "Receive",
  data() {
    return {
      // 总条数
      total: 0,
      // 物料表格数据
      materialList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        materialName: undefined,
        factory: undefined,
        self: false,
        monthOrWeek: "1",
        date: undefined
      },
      // 表单参数
      addForm: {
        date: undefined,
        monthOrWeek: undefined,
      },
      addList: [],

      editOpen: false,
      editForm: {
        id: undefined,
        parentId: undefined,
        materialName: undefined,
        specification: undefined,
        articleNo: undefined,
        factory: undefined,
        unit: undefined,
        num: 0,
        materialType: undefined,
        monthOrWeek: undefined,
        remark: undefined
      },

      projectList: [],

      // 表单校验
      rules: {
        date: [
          {required: true, message: "数据周期不能为空", trigger: "change"}
        ],
        materialName: [
          {required: true, message: "物料名称不能为空", trigger: "blur"}
        ],
        specification: [
          {required: true, message: "物料规格不能为空", trigger: "blur"}
        ],
        articleNo: [
          {required: true, message: "品牌/货号不能为空", trigger: "blur"}
        ],
        factory: [
          {required: true, message: "厂商不能为空", trigger: "blur"}
        ],
        unit: [
          {required: true, message: "单位不能为空", trigger: "blur"}
        ],
        num: [
          {required: true, message: "领取量不能为空", trigger: "blur"}
        ],
        materialType: [
          {required: true, message: "物料类型不能为空", trigger: "change"}
        ],
        monthOrWeek: [
          {required: true, message: "月/周数据不能为空", trigger: "change"}
        ]
      },
      unitOptions: ['个', '张', '卷', '支']
    };
  },
  created() {
    this.getList();
    this.getProjectList();
  },
  methods: {
    /** 查询物料列表 */
    getList() {
      listMaterial(this.queryParams).then(res => {
        this.materialList = res.data.records;
        this.total = res.data.total;
      })
    },
    getProjectList() {
      listProject({type: '2'}).then(res => {
        this.projectList = res.data
      })
    },
    selectableHandler(row, index) {
      return row.num > row.receivedNum
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.editOpen = false;
      this.reset();
    },
    // 对话框关闭回调
    dialogClose() {
      this.open = false;
      this.editOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.addForm = {
        date: undefined,
        monthOrWeek: undefined,
      };
      this.addList = []
      this.$refs.materialList.clearSelection();
      this.resetForm("addForm");
      this.editForm = {
        id: undefined,
        parentId: undefined,
        materialName: undefined,
        specification: undefined,
        articleNo: undefined,
        factory: undefined,
        unit: undefined,
        num: 0,
        materialType: undefined,
        monthOrWeek: undefined,
        remark: undefined
      }
      this.resetForm("editForm");
    },
    radioChange() {
      this.queryParams.date = undefined;
      this.getList();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.handleQuery();
    },
    handleSelectionChange(val) {
      if (val.length === 0) {
        this.addList = []
        return;
      }
      let temp = _.cloneDeep(val)
      let dateArr = []
      temp.forEach(item => {
        if (dateArr.indexOf(item) < 0) {
          dateArr.push(item.recordDate)
        }
      })

      if (dateArr.length > 1) {
        this.$message.warning("多条数据不属于同月，请重新选择")
        this.$refs.materialList.clearSelection()
        this.addList = []
        return
      }

      this.addList = temp.map(item => {
        item.parentId = item.id
        item.num = undefined
        item.id = undefined
        return item
      })
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getList();
    },
    getPickerOptions(type) {
      if (type === 'month') {
        return {
          disabledDate: time => time.getTime() < DateUtil.unix(DateUtil.afterMonth()) * 1000
        }
      }
      if (type === 'week') {
        let limitTime = 0
        if (this.addList.length > 0) {
          DateUtil.lastDayOfMonth(DateUtil.beforeMonth(this.addList[0].recordDate))
          limitTime = DateUtil.unix(this.addList[0].recordDate + '-01') * 1000
        }
        let nextWeekFirstDay = DateUtil.unix(DateUtil.firstDayOfNextWeek()) * 1000;
        limitTime = limitTime < nextWeekFirstDay ? nextWeekFirstDay : limitTime;
        return {
          firstDayOfWeek: 1,
          disabledDate: time => time.getTime() <= limitTime
        }
      }
    },
    showEditBtn(row) {
      if (row.monthOrWeek === '1') {
        if (row.receivedNum > 0) {
          return false;
        }
        if (DateUtil.getMinutes() < DateUtil.getMinutes(DateUtil.day(DateUtil.month() + '25'))) {
          return DateUtil.unix(row.recordDate) >= DateUtil.unix(DateUtil.afterMonth())
        } else {
          return DateUtil.unix(row.recordDate) >= DateUtil.unix(DateUtil.afterMonth())
        }
      } else {
        let split = row.recordDate.split("~");
        let date = split[0];
        let minutes = DateUtil.unix(date);
        let minutes1 = DateUtil.unix(DateUtil.afterWeek());
        return minutes >= minutes1
      }
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.addForm.monthOrWeek = '1'
      this.title = "添加月物料计划";
      this.addList.push({
        id: undefined,
        materialName: undefined,
        specification: undefined,
        articleNo: undefined,
        factory: undefined,
        unit: undefined,
        num: 0,
        price: 0,
        projectId: undefined,
        materialType: undefined,
        monthOrWeek: '1',
        remark: undefined
      })
      this.open = true;
    },
    addRow() {
      this.addList.push({
        id: undefined,
        materialName: undefined,
        specification: undefined,
        articleNo: undefined,
        factory: undefined,
        unit: undefined,
        num: 0,
        price: 0,
        projectId: undefined,
        materialType: undefined,
        monthOrWeek: '1',
        remark: undefined
      })
    },
    deleteRow(row) {
      if (this.addList.length === 1) {
        this.addList = [
          {
            id: undefined,
            materialName: undefined,
            specification: undefined,
            articleNo: undefined,
            factory: undefined,
            unit: undefined,
            num: 0,
            price: 0,
            projectId: undefined,
            materialType: undefined,
            monthOrWeek: '1',
            remark: undefined
          }
        ]
        return
      }
      let index = this.addList.indexOf(row);
      this.addList.splice(index, 1)

    },
    handleExport() {
      exportMaterial(this.queryParams)
    },
    /** 周数据填报操作 */
    handleSplit() {
      this.addForm.id = undefined;
      this.addForm.monthOrWeek = '2'
      this.title = "添加周物料计划";
      this.open = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.editForm = row
      if (this.editForm.monthOrWeek === '1') {
        this.$set(this.editForm, 'date', row.recordDate)
      } else {
        let split = row.recordDate.split('~');
        this.$set(this.editForm, 'date', split[0])
      }
      this.editOpen = true
    },

    /** 提交按钮 */
    submitForm() {
      if (this.addList.length === 0) {
        return
      }
      let checkKeys = ['materialName', 'specification', 'articleNo', 'factory', 'unit', 'num', 'materialType']
      let validFlag = true
      this.addList.forEach(item => {
        for (let key in item) {
          if (checkKeys.indexOf(key) > -1) {
            if (item[key] === null || item[key] === undefined || item[key] === '' || item[key] === 0) {
              validFlag = false
            }
          }
        }
      })
      if (!validFlag) {
        this.$message.error("必填项不能为空")
        return;
      }
      this.$refs["addForm"].validate(valid => {
        if (valid) {
          let data = {
            date: this.addForm.date,
            monthOrWeek: this.addForm.monthOrWeek,
            addList: this.addList
          }
          addMaterial(data).then(res => {
            this.$message.success("添加成功");
            this.open = false;
            this.getList();
          });

        }
      });
    },

    submitEditForm() {
      this.$refs["editForm"].validate(valid => {
        if (valid) {
          updateMaterial(this.editForm).then(res => {
            this.$message.success("修改成功");
            this.editOpen = false;
            this.getList();
          });

        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除编号为"' + row.id + '"的数据项？').then(() => {
        return delMaterial(row.id);
      }).then(() => {
        this.getList();
        this.$message.success("删除成功");
      }).catch(() => {
      });
    },
  }
};
</script>

<style scoped lang="scss">
.add-table::v-deep.el-table .cell {
  padding-left: 2px;
  padding-right: 2px;
}

.add-table::v-deep.el-table th.el-table__cell > .cell {
  padding-left: 5px;
  padding-right: 5px;
}
</style>
