<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:plan:add']"
          >添加计划</el-button
        >
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="planList"
      border
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="月份" align="center" prop="month" />
      <el-table-column label="作业中段名称" align="center" prop="middleName" />
      <el-table-column label="总计划量" align="center" prop="amount" />
      <el-table-column label="总开采量" align="center" prop="mining" />
      <el-table-column label="差值" align="center" prop="difference" />
      <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-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:plan:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="addKcl(scope.row)"
            >开采量</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:plan:remove']"
            >删除</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"
    />

    <!-- 添加或修改生产计划对话框 -->
    <!-- 


      [
      
      {month:2022-06,name:114-11,}
      ]
     -->
    <el-dialog
      title="开采量"
      :visible.sync="openkcl"
      width="900px"
      append-to-body
    >
      <div style="margin-bottom: 10px">{{ formMonth }}</div>
      <div
        style="margin-bottom: 10px"
        v-for="(item, index) in kclList"
        :key="item.id"
      >
        <el-input
          placeholder="请输入开采量"
          style="width: 90%"
          v-model="item.mining"
          @input="kclblur(item.mining, index)"
        >
          <template slot="prepend">{{ item.middleName }}</template>
        </el-input>
        吨
      </div>
      <div slot="footer" class="dialog-footer">
        <span class="item" style="float: left"
          >总开采量：<span style="color: #f56c6c"> {{ kcltot }}</span> 吨</span
        >
        <el-button type="primary" @click="submitForm1">确 定</el-button>
        <el-button @click="cancel1">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <div></div>
      <div style="margin-bottom: 5px">
        月<span style="visibility: hidden">月份</span>份：
        <el-date-picker
          v-model="planChoiceMonth"
          type="month"
          placeholder="选择月"
          @change="nowMonth"
          :clearable="false"
          :editable="false"
        >
        </el-date-picker>
      </div>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row :gutter="20">
          <!-- <el-col :span="7">
            <el-form-item label="月份" prop="month">
              
            </el-form-item>
          </el-col> -->
          <el-col :span="10">
            <!-- <el-form-item label="作业中段名称" prop="middleName">
              <el-input
                v-model="form.middleName"
                placeholder="请输入作业中段名称"
              />
            </el-form-item> -->
            作业中段：

            <el-select v-model="planChoiceName" placeholder="请选择作业中段">
              <el-option
                v-for="item in zhongduanList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="10">
            计划开采量：<el-input
              v-model="planChoiceAmount"
              type="number"
              placeholder="请输入数字"
              style="width: 70%"
            ></el-input
            >吨
            <!-- <el-form-item label="计划量" prop="amount">
              <el-input v-model="form.amount" placeholder="请输入计划量" />
            </el-form-item> -->
          </el-col>
          <el-col :span="2">
            <el-button
              :disable="plandisabled"
              type="success"
              icon="el-icon-plus"
              @click="addPlanList"
            >
              新增一条</el-button
            >
          </el-col>
        </el-row>
      </el-form>
      <div>
        <todo-item
          v-for="(item, index) of planValue"
          :key="index"
          :content="item"
          :index="index"
          @delete="mydelete"
        ></todo-item>
      </div>
      <div slot="footer" class="dialog-footer">
        <span class="item" style="float: left"
          >总计划开采量：<span style="color: #f56c6c"> {{ countPlan }}</span>
          吨</span
        >
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listMiddle,
  getMiddle,
  delMiddle,
  addMiddle,
  updateMiddle,
} from "@/api/reSave/middle";
import {
  listPlan,
  getPlan,
  delPlan,
  addPlan,
  updatePlan,
  getUpdateList,
  addMin,
  testAdd,
} from "@/api/reSave/prodPlan";
import { selfTime } from "@/assets/time.js";
import TodoItem from "@/views/reSave/prodPlan/TodoItem";
export default {
  name: "Plan",
  components: {
    "todo-item": TodoItem,
  },
  data() {
    return {
      kcltotarr: [],
      kcltot: null,
      kclList: [{ name: "zhongduan", value: null }],
      openkcl: false,
      valid: false,
      countPlan: 0,
      plandisabled: false,
      planValue: [],
      inputValue: "",
      planChoiceMonth: "",
      planChoiceName: "",
      planChoiceAmount: "",
      list: [],
      zhongduanList: [
        {
          value: "中段1",
          label: "中段1",
        },
        {
          value: "中段2",
          label: "中段2",
        },
        {
          value: "中段3",
          label: "中段3",
        },
        {
          value: "中段4",
          label: "中段4",
        },
        {
          value: "中段5",
          label: "中段5",
        },
      ],
      zhongduanVal: "",
      //新增计划月份选择
      newMonth: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生产计划表格数据
      planList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        month: null,
        middleName: null,
        amount: null,
        mining: null,
      },

      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      //选中月份
      formMonth: null,
      addList: [{ month: "2022-06", zdname: "老6", planNum: "33" }],
    };
  },
  created() {
    this.getList();
  },
  watch: {
    kclList(newVal, oldVal) {
      // console.log(newVal, this.kclList, 111);
    },
  },
  methods: {
    kclblur(e, index) {
      this.kcltotarr[index] = e;
      this.kcltot = 0;
      for (let i = 0; i < this.kcltotarr.length; i++) {
        this.kcltot += Number(this.kcltotarr[i]);
      }
    },
    submit() {
      this.list.push(this.inputValue);
      this.inputValue = "";
    },
    mydelete(index) {
      let that = this;
      this.$modal.confirm("是否确认删除？").then(function () {
        let plancount = 0;

        that.planValue.splice(index, 1);
        for (let i = 0; i < that.planValue.length; i++) {
          plancount += Number(that.planValue[i].amount);
        }
        that.countPlan = plancount;
        // return that.planValue;
      });
      // console.log(index, "del");

      // console.log(this.planValue, "delplanValue");
    },
    nowMonth(e) {
      this.formMonth = `${selfTime(e).myYear}-${selfTime(e).myMonth}`;
      // console.log(e, this.formMonth);
    },
    addPlanList() {
      // console.log(this.formMonth);
      testAdd({ month: this.formMonth })
        .then((res) => {
          if (res.code == 500) {
            this.$modal.alertWarning("该月份已存在");
          } else if (res.code == 200) {
            if (this.formMonth == "" || this.formMonth == null) {
              this.$modal.alertWarning("月份不可为空");
              return;
            }
            if (this.planChoiceName == "" || this.planChoiceName == null) {
              this.$modal.alertWarning("中段不可为空");
              return;
            }

            if (this.planChoiceAmount == "" || this.planChoiceAmount == null) {
              this.$modal.alertWarning("计划采量不可为空");
              return;
            }
            if (this.planValue.length < 5) {
              let plancount = 0;
              let planMonth = this.formMonth,
                planMidname = this.planChoiceName,
                planAmount = this.planChoiceAmount;
              this.planValue.push({
                month: planMonth,
                middleName: planMidname,
                amount: planAmount,
              });
              this.planChoiceName = null;
              this.planChoiceAmount = null;
              // console.log(this.planValue, "this.planValue");
              for (let i = 0; i < this.planValue.length; i++) {
                plancount += Number(this.planValue[i].amount);
              }
              // console.log(plancount);
              this.countPlan = plancount;
            } else {
              this.$modal.alertWarning("最多添加5条");
            }
          }
        })
        .then(() => {});
    },
    getMidList() {
      this.zhongduanList = [];
      listMiddle({ pageNum: 1, pageSize: 999 }).then((response) => {
        // console.log(response.rows);
        let data = response.rows;
        for (let i = 0; i < data.length; i++) {
          this.zhongduanList.push({
            value: data[i].name,
            label: data[i].name,
          });
        }
        // this.middleList = response.rows;
        // this.total = response.total;
        // this.loading = false;
      });
    },
    // 手动添加开采量
    addKcl(msg) {
      this.kclList = [];
      this.kcltotarr = [];

      this.kcltot = 0;
      let month = msg.month;
      this.formMonth = month;
      // console.log(month);
      getUpdateList({ month: month })
        .then((response) => {
          // console.log(response);
          let data = response.rows;
          let updateArr = [];
          for (let i = 0; i < data.length; i++) {
            updateArr.push({
              id: data[i].id,
              month: data[i].month,
              middleName: data[i].middleName,
              mining: data[i].mining,
            });
          }
          // console.log(updateArr);
          this.kclList = updateArr;

          this.openkcl = true;
        })
        .then(() => {
          for (let i = 0; i < this.kclList.length; i++) {
            this.kcltotarr.push(this.kclList[i].mining);
          }
          // console.log(this.kcltotarr, " this.kcltotarr");
        })
        .then(() => {
          for (let i = 0; i < this.kcltotarr.length; i++) {
            this.kcltot += Number(this.kcltotarr[i]);
          }
        });
    },
    /** 查询生产计划列表 */
    getList() {
      this.loading = true;
      listPlan(this.queryParams).then((response) => {
        // console.log(response);

        this.planList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        month: null,
        middleName: null,
        amount: null,
        mining: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.valid = false;
      this.formMonth = null;
      this.planValue = [];
      this.countPlan = 0;
      this.planChoiceMonth = null;
      this.getMidList();
      this.reset();
      this.open = true;
      this.title = "添加生产计划";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.valid = true;
      this.getMidList();
      this.reset();
      let month = row.month;
      this.planChoiceMonth = month;
      this.formMonth = month;
      getUpdateList({ month: month }).then((response) => {
        // console.log(response);
        let data = response.rows;
        let updateArr = [];
        for (let i = 0; i < data.length; i++) {
          updateArr.push({
            id: data[i].id,
            month: data[i].month,
            middleName: data[i].middleName,
            amount: data[i].amount,
          });
        }
        this.planValue = updateArr;
        this.planChoiceAmount = null;
        let plancount = 0;
        for (let i = 0; i < this.planValue.length; i++) {
          plancount += Number(this.planValue[i].amount);
        }
        this.countPlan = plancount;

        this.open = true;
        this.title = "修改生产计划";
      });
    },
    cancel1() {
      this.openkcl = false;
    },

    // 开采量提交addMin
    submitForm1() {
      // console.log(this.kclList);
      // let newArr=[];
      // for (let i = 0; i < this.kclList.length; i++) {
      //   delete this.kclList[i].month;
      // }
      addMin(this.kclList).then((response) => {
        this.$modal.msgSuccess("修改成功");
        this.open = false;
        this.getList();
      });
      // addMin().then()
      this.openkcl = false;
    },
    /** 提交按钮 */
    submitForm() {
      // console.log(this.valid);
      if (this.valid) {
        if (this.planValue.length > 0) {
          updatePlan(this.planValue).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
        } else {
          this.$modal.alertWarning("请添加数据");
        }
      } else {
        if (this.planValue.length > 0) {
          addPlan(this.planValue).then((response) => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
        } else {
          this.$modal.alertWarning("请添加数据");
        }
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      // const ids = row.id || this.ids;
      // console.log(row);
      let month = row.month;
      this.$modal
        .confirm("是否确认删除？")
        .then(function () {
          return delPlan({ month: month });
          // delPlan()
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/plan/export",
        {
          ...this.queryParams,
        },
        `plan_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
