<template>
  <div class="app-container">
    <!--    搜索框-->
    <div class="card-change">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="" prop="tankName">
          <el-input
            v-model="queryParams.tankName"
            placeholder="请输入油罐名称"
            clearable
            style="width: 240px;"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="" prop="oilNumber">
          <el-select v-model="queryParams.oilNumber" placeholder="请选择油品油号" style="width:300px"
                     @change="chooseOilNumber()" :disabled="disableInput">
            <el-option
              v-for="option in selectOilTypeByPrice"
              :key="option.numberId"
              :label="option.oilType +' '+option.oilName"
              :value="option.oilType +' '+option.oilName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="">
          <el-date-picker
            v-model="beginTime"
            style="width: 160px"
            type="date"
            placeholder="开始日期">
          </el-date-picker>
          至
          <el-date-picker
            v-model="endTime"
            style="width: 160px"
            type="date"
            placeholder="结束日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item style="float: right;margin-right: 0px ">
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          <el-button
            type="primary"
            @click="tankAdd"
            v-hasPermi="['oilConfig:oilTank:list:add']"
          >新增油罐
          </el-button>
        </el-form-item>
      </el-form>
      <!--    </div>-->

      <!--     列表-->
      <div style="height: 70vh;overflow: auto">
        <el-table ref="tables"
                  v-loading="loading"
                  :data="tankList"
                  border
                  :default-sort="defaultSort">
          <el-table-column align="center" type="index" label="序号"></el-table-column>
          <el-table-column label="油罐名称" align="center" prop="tankName"/>
          <el-table-column label="油品-油号" align="center" prop="oilNumber"/>
          <el-table-column label="油罐容量" align="center" prop="tankVolume"/>
          <el-table-column label="下限预警" align="center" prop="lowerWarning"/>
          <el-table-column label="油品密度" align="center" prop="oilDensity"/>
          <el-table-column label="存油数量" align="center" prop="storedQuantity"/>
          <el-table-column label="存油总价(元)" align="center" prop="totalPrice"/>
          <el-table-column label="成本价(元/升)" align="center" prop="discountedPrice"/>
          <el-table-column label="油罐状态" align="center" prop="discountedPrice">
            <template slot-scope="scope">
              <el-switch
                disabled
                v-model="scope.row.status"
                active-value="启用"
                inactive-value="禁用"
                @change="changeStatus(scope.row)"
                active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>

            </template>
          </el-table-column>
          <el-table-column label="操作人" align="center" prop="realName"/>

          <el-table-column label="操作时间" align="center" prop="updateTime" width="200">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.updateTime) }}</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"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['oilConfig:oilTank:list:update']"
              >修改
              </el-button>
              <el-button
                size="mini"
                type="text"
                @click="handleClean(scope.row)"
                v-hasPermi="['oilConfig:oilTank:list:del']"
              >初始化
              </el-button>

            </template>
          </el-table-column>
        </el-table>
      </div>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!--     新增/修改-->
    <el-dialog :title="title" :visible.sync="open" width="30%" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="tankForm" :rules="rules" label-width="80px">
        <el-form-item label="油罐名称" prop="tankName">
          <el-input v-model="tankForm.tankName" placeholder="请输入油罐名称" />
        </el-form-item>
        <el-form-item label="油品油号" prop="oilNumber">
          <el-select v-model="tankForm.numberId" placeholder="请选择油品油号" style="width:100%"
                     @change="chooseOilNumber()" :disabled="disableInput">
            <el-option
              v-for="option in selectOilTypeByPrice"
              :key="option.numberId"
              :label="option.oilType +' '+option.oilName"
              :value="option.numberId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="油罐体积" prop="tankVolume">
          <el-input v-model="tankForm.tankVolume" placeholder="请输入油罐体积" maxlength="30" @change="changeNumber"
                     :disabled="disableInput">
            <template slot="append">{{ tankForm.unit }}</template>
          </el-input>
        </el-form-item>
        <el-form-item label="下限预警" prop="lowerWarning">
          <el-input v-model="tankForm.lowerWarning" placeholder="小于预警值将进行提示"
                    maxlength="30">
            <template slot="append">{{ tankForm.unit }}</template>
          </el-input>
        </el-form-item>
        <template v-if="title == '修改油罐'">
          <el-form-item label="油品密度" prop="oilDensity">
            <el-input v-model="tankForm.oilDensity" placeholder="请输入油品密度" :disabled="true"
                      maxlength="30" @input="getSecondName()">
              <template slot="append">g/ml</template>
            </el-input>
          </el-form-item>
          <el-form-item label="存油数量" prop="storedQuantity">
            <el-input v-model="tankForm.storedQuantity" placeholder="请输入存油数量" maxlength="30"
                      :disabled="true" pattern="^\d+(\.\d+)?$" @change="changeNumber" @input="changePrice() ">
              <template slot="append">{{ tankForm.unit }}</template>
            </el-input>
          </el-form-item>
          <!--        <el-form-item label="存油总价" prop="totalPrice" >-->
          <!--          <el-input v-model="tankForm.totalPrice" placeholder="请输入存油总价" style="width:300px" maxlength="30" :disabled="true"  @input="changePrice()" @change="changeNumber" >-->
          <!--            <template slot="append">元</template>-->
          <!--          </el-input>-->
          <!--        </el-form-item>-->
          <el-form-item label="折合单价" prop="discountedPrice">
            <el-input v-model="tankForm.discountedPrice" placeholder="请输入折合单价" maxlength="30"
                      :disabled="true">
              <template slot="append">元{{ tankForm.unit ? "/" + tankForm.unit : '' }}</template>
            </el-input>
          </el-form-item>
        </template>

        <el-form-item label="油罐状态" prop="status">
          <el-radio-group v-model="tankForm.status">
            <el-radio
              v-for="dict in statusList"
              :key="dict"
              :label="dict"
              :value="dict"
              @change="handleIsopenSelect"
            />
          </el-radio-group>
        </el-form-item>
        <!--        <el-form-item label="库存统计" prop="inventoryStatistics">-->
        <!--          <el-radio-group v-model="tankForm.inventoryStatistics">-->
        <!--            <el-radio-->
        <!--              v-for="dict in dict.type.zhzt"-->
        <!--              :key="dict.value"-->
        <!--              :label="dict.label"-->
        <!--              :value="dict.value"-->
        <!--              @change="handleIsopenSelect"-->
        <!--            />-->
        <!--          </el-radio-group>-->
        <!--        </el-form-item>-->
        <el-form-item label="备注信息">
          <el-input type="textarea" v-model="tankForm.remarks"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import {cleanTankApi, exportExcelTankApi, getTankApi, insertTankApi, updateTankApi} from "@/api/oilConfig/oilTank";
import {getName, parseTime} from "../../../utils/fuint";
import {addStaff, updateStaff} from "@/api/staff/staff";
import {getOilNameListApi} from "@/api/oilPrice";
import {BigNumber} from 'bignumber.js';
import {changeAccountStatus} from "@/api/system/account";


export default {
  name: 'oilTank',
  dicts: ['zhzt'],

  data() {
    var valiNumberPass = (rule, value, callback) => {//包含小数的数字
      let reg = /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g;
      if (value === '') {
        callback(new Error('请输入内容'));
      } else if (!reg.test(value)) {
        callback(new Error('请输入数字'));
      } else if (value.length > 8) {
        callback(new Error('数字长度不得超过8位'));
      } else {
        callback();
      }
    };

    return {
      // 表单名称
      title: '',
      tankList: [], // 油罐列表
      statusList: ['启用', '禁用'],
      tankForm: {
        id: null,
        tankName: '',
        oilNumber: '',
        tankVolume: null,
        lowerWarning: null,
        oilDensity: 0,
        storedQuantity: 0,
        totalPrice: 0,
        discountedPrice: 0,
        status: '',
        inventoryStatistics: '',
        remarks: '',
        storeId: null,
        numberId: null,
        createTime: null,
        updateTime: null,
        unit: ''
      },
      disableInput: false, // 默认不禁用
      // 是否显示弹出层
      open: false,
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        tankName: '',
        page: null,
        pageSize: null
      },
      beginTime: "",
      endTime: "",
      unit: 'L',
      // 查询全部油品
      selectOilTypeByPrice: [],
      // 显示搜索条件
      showSearch: true,
      // 遮罩层
      loading: false,
      // 默认排序
      defaultSort: {prop: 'createTime', order: 'descending'},
      // 表单校验
      rules: {
        tankName: [
          {required: true, message: "油罐名称不能为空", trigger: "blur"},
        ],
        oilNumber: [
          {required: true, message: '请选择油品类型', trigger: 'change'}
        ],
        tankVolume: [
          {required: true, validator: valiNumberPass, trigger: "blur"}
        ],
        lowerWarning: [
          {required: true, validator: valiNumberPass, trigger: "blur"}
        ],
        oilDensity: [
          {required: true, validator: valiNumberPass, trigger: "blur"}
        ],
        storedQuantity: [
          {required: true, validator: valiNumberPass, trigger: "blur"}
        ],
        totalPrice: [
          {required: true, validator: valiNumberPass, trigger: "blur"}
        ],
        discountedPrice: [
          {required: true, validator: valiNumberPass, trigger: "blur"}
        ],
        status: [
          {required: true, message: "请选择对应状态", trigger: "blur"}
        ],
        inventoryStatistics: [
          {required: true, message: "请选择对应状态", trigger: "blur"}
        ]
      }
    }
  },
  watch: {
    open(newValue) {
      if (!newValue) {
        let this_ = this
        this_.getList()
      }
    }
  },
  async created() {
    let this_ = this
    await this_.getList()
    this.getOilNameList() // 查询全部油品
  },
  methods: {
    handleIsopenSelect() {
      this.$forceUpdate()
    },
    getList() {
      this.loading = true;
      let dateRange = []
      if (this.beginTime && this.endTime) {
        dateRange.push(this.beginTime.toLocaleDateString())
        dateRange.push(this.endTime.toLocaleDateString())
      }
      getTankApi(this.addDateRange(this.queryParams, dateRange)).then(response => {
        this.tankList = response.data.records;
        this.total = response.data.total;
      })
      this.loading = false;
    },


    // 提交按钮
    submitForm: function () {
      this.$refs["form"].validate(valid => {

        if (valid) {

          if (!this.tankForm.id) {
            insertTankApi(this.tankForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          } else {
            updateTankApi(this.tankForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    changeStatus(data) {
      updateTankApi(data).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.open = false;
        this.getList();
      });
    },
    // 修改操作
    handleUpdate(data) {
      this.disableInput = true
      let this_ = this
      this_.tankForm = data
      this_.open = true;
      this_.title = "修改油罐";
      this.getOilNameList() // 查询全部油品

    },
    // 初始化油罐信息
    handleClean(data) {
      this.$confirm('此操作将初始化油罐库存信息,请谨慎操作!是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        cleanTankApi(data).then(response => {
          this.$message({
            type: 'success',
            message: '初始化成功!'
          });
          this.getList();
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });


    },
    // 取消按钮
    cancel() {
      this.open = false;
      // this.reset();
    },
    // 搜索按钮操作
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    resetQuery() {
      this.queryParams = {
        tankName: '',
        page: null,
        pageSize: null
      };
      this.beginTime = ''
      this.endTime = ''
      this.getList();
    },
    // 新增油罐
    tankAdd() {
      // 表单重置
      let this_ = this
      this_.recharge()
      // this_.tankForm.status= '启用',
      // this_.tankForm.inventoryStatistics= '启用',
      this_.disableInput = false

      this_.open = true;
      this_.title = "新增油罐";
      this.getOilNameList() // 查询全部油品
    },
    recharge() {
      this.tankForm = {
        id: null,
        tankName: '',
        oilNumber: '',
        tankVolume: null,
        lowerWarning: null,
        oilDensity: 0,
        storedQuantity: 0,
        totalPrice: 0,
        discountedPrice: 0,
        status: '启用',
        inventoryStatistics: '启用',
        remarks: '',
        storeId: null,
        numberId: null,
        createTime: null,
        updateTime: null,
        unit: ''
      }
    },
    // 选择油品号之后
    chooseOilNumber() {
      let this_ = this;
      this_.selectOilTypeByPrice.forEach(oilType => {
        if (oilType.numberId == this_.tankForm.numberId) {
          this.tankForm.oilDensity = oilType.oilDensity
          this_.tankForm.oilNumber = oilType.oilType + " " + oilType.oilName
          this_.tankForm.unit = oilType.unit
        }
      })
    },

    changePrice() {
      var this_ = this


      if (this_.tankForm.totalPrice != null && this_.tankForm.storedQuantity != null) {
        if (!this.checkNumeric(this_.tankForm.totalPrice)) {
          this_.tankForm.totalPrice = 0
        }
        if (!this.checkNumeric(this_.tankForm.storedQuantity)) {
          this_.tankForm.storedQuantity = 0
        }

        var totalPrice = BigNumber(this_.tankForm.totalPrice);
        var storedQuantity = BigNumber(this_.tankForm.storedQuantity);
        // this_.tankForm.discountedPrice = totalPrice.dividedBy(storedQuantity).toNumber();
        this_.tankForm.discountedPrice = parseFloat(totalPrice.dividedBy(storedQuantity).toFixed(2));

      }
    },
    changeNumber() {
      var this_ = this


      // console.log("this_.tankForm.tankVolume",this_.tankForm.tankVolume)
      // console.log("this_.tankForm.storedQuantity",this_.tankForm.storedQuantity)

      // if (this_.tankForm.tankVolume)
      if (parseFloat(this_.tankForm.storedQuantity) > parseFloat(this_.tankForm.tankVolume)) {
        console.log("Stored quantity exceeds tank volume");
        this_.tankForm.storedQuantity = parseFloat(this_.tankForm.tankVolume);
      }

      if (this_.tankForm.totalPrice != null) {
        if (!this.checkNumeric(this_.tankForm.totalPrice)) {
          this_.tankForm.totalPrice = 0
        } else {
          this_.tankForm.totalPrice = parseFloat(this_.tankForm.totalPrice).toFixed(2);

        }
      }
      if (this_.tankForm.storedQuantity != null) {
        if (!this.checkNumeric(this_.tankForm.storedQuantity)) {
          this_.tankForm.storedQuantity = 0
        } else {
          this_.tankForm.storedQuantity = parseFloat(this_.tankForm.storedQuantity).toFixed(2);

        }
      }

    },

    checkNumeric(value) {
      // 使用JavaScript的方法判断是否为数字
      let isNumeric = !isNaN(parseFloat(value)) && isFinite(value);
      return isNumeric
    },
    // isNumeric(value) {
    //   return typeof value === 'number' && isFinite(value);
    // },

    getOilNameList() {
      var this_ = this
      getOilNameListApi().then(response => {
        var list = response.data
        this_.selectOilTypeByPrice = list
      });
    },
    getSecondName() {
      this.$forceUpdate();
    }
  },
};

</script>

<style>
.app-container {
  width: 100%;
  height: 100vh;
  background: #f6f8f9;
}

.el-form--inline .el-form-item {
  margin-right: 44px;
}

</style>
