<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="日期" prop="dataDate">
        <el-date-picker clearable
                        v-model="queryParams.dataDate"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择日期" @change="handleQuery">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="机台号" prop="deviceId">
        <el-select
            v-model="queryParams.deviceId"
            placeholder="请选择机台号"
            filterable
            style="width: 80px"
            @change="handleQuery"
        >
          <el-option
              v-for="item in deviceOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="时段" prop="remark">
        <el-select v-model="queryParams.remark" placeholder="选择时段" style="width: 180px" @change="handleQuery">
          <el-option
              v-for="dict in in_out_time"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>

<!--      <el-form-item>-->
<!--        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>-->
<!--        <el-button icon="Refresh" @click="resetQuery">重置</el-button>-->
<!--      </el-form-item>-->
    </el-form>

    <el-table v-loading="loading" :data="calcSpecList" show-summary :summary-method="getSummaries"
              @selection-change="handleSelectionChange">
      <el-table-column label="日期" align="center" prop="dataDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.dataDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="小时" align="center" prop="hour"/>
      <el-table-column label="机台号" align="center" prop="deviceId"/>
      <el-table-column label="织造米数" align="center" prop="length"/>
      <el-table-column label="规格" align="center" prop="spec"/>
      <el-table-column label="毛高" align="center" prop="height"/>
      <el-table-column label="米克重" align="center" prop="mick"/>
      <el-table-column label="密度" align="center" prop="density"/>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">核对</el-button>
              </template>
            </el-table-column>
    </el-table>

    <!-- 添加或修改按配方1小时统计数据对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="calcSpecRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="日期" prop="dataDate">
          <el-date-picker disabled
                          v-model="form.dataDate"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="小时" prop="hour">
          <el-input v-model="form.hour" disabled />
        </el-form-item>
        <el-form-item label="机台号" prop="deviceId">
          <el-input v-model="form.deviceId" disabled />
        </el-form-item>
        <el-form-item label="织造米数" prop="length">
          <el-input-number v-model="form.length" placeholder="请输入织造米数" style="width: 180px"/>
        </el-form-item>
        <el-form-item label="密度" prop="density">
          <el-input-number v-model="form.density" placeholder="请输入密度" style="width: 180px"/>
        </el-form-item>
        <el-form-item label="规格" prop="spec">
          <el-input v-model="form.spec" disabled/>
        </el-form-item>
        <el-form-item label="毛高" prop="height">
          <el-input v-model="form.height" disabled/>
        </el-form-item>
        <el-form-item label="米克重" prop="mick">
          <el-input v-model="form.mick" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CalcSpec">
import {addCalcSpec, delCalcSpec, getCalcSpec, listCalcSpec, updateCalcSpec} from "@/api/calc/calcSpec";
import {listDevice} from "@/api/biz/device"

const {proxy} = getCurrentInstance();
const {in_out_time} = proxy.useDict('in_out_time');
const calcSpecList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const deviceOptions = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 100,
    dataDate: new Date(new Date().getTime() - 31 * 60 * 60 * 1000).Format('yyyy-MM-dd'),
    hour: null,
    deviceId: null,
    length: null,
    spec: null,
    height: null,
    mick: null,
    density: null,
    price: null,
    remark: null
  },
  rules: {
    density: [
      { required: true, message: "密度不能为空", trigger: "blur" },
      { type: "number", message: "密度必须为数字值", trigger: "blur" },
      {
        validator: (rule, value, callback) => {
          if (value <= 0) {
            callback(new Error('密度必须大于0'));
          } else {
            callback();
          }
        },
        trigger: "blur"
      }
    ],
    length: [
      { required: true, message: "织造米数不能为空", trigger: "blur" },
      { type: "number", message: "织造米数必须为数字值", trigger: "blur" },
      {
        validator: (rule, value, callback) => {
          if (value <= 0) {
            callback(new Error('织造米数必须大于0'));
          } else {
            callback();
          }
        },
        trigger: "blur"
      }
    ]
  }
});

const {queryParams, form, rules} = toRefs(data);

function getDevice() {
  listDevice({online: 1, pageNum: 1, pageSize: 1000}).then(response => {
    deviceOptions.value = response.rows.map(item => ({
      value: item.deviceId,
      label: item.deviceId
    }));
  }).catch(error => {
    console.error('获取机台号列表失败:', error);
    proxy.$modal.notifyError('获取机台号列表失败');
  });
}


/** 查询按配方1小时统计数据列表 */
function getList() {
  loading.value = true;
  if (!queryParams.value.deviceId) {
    queryParams.value.deviceId = 1;
  }
  if (!queryParams.value.remark) {
    queryParams.value.remark = '7-19';
  }
  listCalcSpec(queryParams.value).then(response => {
    calcSpecList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

//自定义方法
function getSummaries(param) {
  const {columns, data} = param;
  const sums = {};
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计';
      return;
    }
    if (index != 3) {
      sums[index] = '';
      return;
    }
    const values = data.map(item => Number(item[column.property]));
    if (!values.every(value => isNaN(value))) {
      sums[index] = values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!isNaN(value)) {
          return prev + curr;
        } else {
          return prev;
        }
      }, 0);
      sums[index] = sums[index].toFixed(2);
    } else {
      sums[index] = 'N/A';
    }
  });
  return sums;
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    dataDate: null,
    hour: null,
    deviceId: null,
    length: null,
    spec: null,
    height: null,
    mick: null,
    density: null,
    price: null,
    remark: null
  };
  proxy.resetForm("calcSpecRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  getDevice();
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加按配方1小时统计数据";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getCalcSpec(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "产量数据核对";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["calcSpecRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateCalcSpec(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCalcSpec(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除按配方1小时统计数据编号为"' + _ids + '"的数据项？').then(function () {
    return delCalcSpec(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('calc/calcSpec/export', {
    ...queryParams.value
  }, `calcSpec_${new Date().getTime()}.xlsx`)
}

getDevice();
getList();
</script>
