<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="60px">
      <el-form-item label="名称" prop="poolName">
        <el-input v-model="queryParams.poolName" placeholder="请输入奖金池名称" clearable />
        <!-- <el-select v-model="queryParams.poolName" placeholder="请选择奖金池名称" clearable>
          <el-option v-for="item in bonusPoolList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select> -->
      </el-form-item>
      <el-form-item label="产线" prop="productionLine">
        <el-select v-model="queryParams.productionLine" placeholder="请选择产线" clearable>
          <el-option v-for="item in productionLineList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建人" prop="createBy">
        <el-input v-model="queryParams.createBy" placeholder="请输入创建人" clearable />
        <!-- <el-select v-model="queryParams.poolName" placeholder="请选择奖金池名称" clearable>
          <el-option v-for="item in bonusPoolList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select> -->
      </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="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-setting" size="mini"
          @click="handlePostCoeffConfig">岗位系数配置</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-document" size="mini"
          @click="handleTemplateManagement">模板管理</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row> -->

    <!-- 奖金池列表 -->
    <el-table v-loading="loading" :data="bonusPoolList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="名称" align="center" prop="poolName" width="150" />
      <el-table-column label="产线" align="center" prop="productionLine" width="150" />
      <el-table-column label="开始时间" align="center" prop="bonusStartTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.bonusStartTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="bonusEndTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.bonusEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总金额(元)" align="center" prop="totalBonus" width="120">
        <template slot-scope="scope">
          <span>{{ Number(scope.row.totalBonus).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
      <el-table-column label="创建人" align="center" prop="createBy" width="150" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)">详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</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="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="名称" prop="poolName">
          <el-input v-model="form.poolName" placeholder="请输入奖金池名称" />
        </el-form-item>
        <el-form-item label="产线" prop="productionLine">
          <muti-select v-model="form.productionLine" placeholder="请选择产线" clearable filterable
            :options="productionLineList">
            <el-option v-for="item in productionLineList" :key="item.value" :label="item.label" :value="item.value" />
          </muti-select>
        </el-form-item>

        <el-form-item label="开始时间" prop="bonusStartTime">
          <el-date-picker v-model="form.bonusStartTime" type="date" placeholder="选择开始时间" value-format="yyyy-MM-dd"
            style="width: 100%" />
        </el-form-item>

        <el-form-item label="结束时间" prop="bonusEndTime">
          <el-date-picker v-model="form.bonusEndTime" type="date" placeholder="选择结束时间" value-format="yyyy-MM-dd"
            style="width: 100%" />
        </el-form-item>

        <el-form-item label="查询重量">
          <el-button type="primary" @click="queryCoilWeight"
            :disabled="!form.bonusStartTime || !form.bonusEndTime || !form.productionLine"
            :loading="queryLoading">查询钢卷总重量</el-button>
        </el-form-item>

        <el-form-item label="总重量(吨)">
          <el-input v-model="totalWeight" disabled placeholder="请先查询钢卷重量" style="width: 100%" />
        </el-form-item>

        <el-form-item label="系数" prop="coeff">
          <el-input-number v-model="form.coeff" :precision="4" :step="0.0001" :min="0" placeholder="请输入系数"
            style="width: 100%" @change="calculateTotalBonus" />
        </el-form-item>

        <el-form-item label="总金额" prop="totalBonus">
          <el-input-number v-model="form.totalBonus" :precision="2" :step="0.01" :min="0" placeholder="自动计算或手动输入"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="4" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog title="奖金池详情" :visible.sync="detailOpen" width="1000px" append-to-body>
      <el-descriptions :column="2" border style="margin-bottom: 20px">
        <el-descriptions-item label="产线">{{ bonusPoolDetail.productionLine }}</el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ parseTime(bonusPoolDetail.bonusStartTime, '{y}-{m}-{d}')
        }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ parseTime(bonusPoolDetail.bonusEndTime, '{y}-{m}-{d}')
        }}</el-descriptions-item>
        <el-descriptions-item label="总金额(元)">{{ Number(bonusPoolDetail.totalBonus).toFixed(2) }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ bonusPoolDetail.remark || '无' }}</el-descriptions-item>
      </el-descriptions>

      <el-divider>奖金分配明细</el-divider>
      <BonusConfig ref="bonusConfigRef" :pool-id="currentPoolId" :total-bonus="bonusPoolDetail.totalBonus"
        :max-adjust-coeff="maxAdjustCoeff" />

      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 岗位系数配置对话框 -->
    <el-dialog title="岗位系数配置" :visible.sync="postCoeffConfigOpen" width="900px" append-to-body>
      <PostCoeffConfig ref="postCoeffConfigRef" :show="postCoeffConfigOpen" @refresh="getList" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="postCoeffConfigOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 模板管理对话框 -->
    <el-dialog title="模板管理" :visible.sync="templateManagementOpen" width="1200px" append-to-body>
      <BonusTemplateManagement :show="templateManagementOpen" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="templateManagementOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBonusPool, getBonusPool, delBonusPool, addBonusPool, updateBonusPool } from "@/api/wms/bonusPool";
import BonusConfig from "./components/BonusConfig.vue";
import PostCoeffConfig from "./components/PostCoeffConfig.vue";
import BonusTemplateManagement from "./components/BonusTemplateManagement.vue";
import { getConfigKey } from '@/api/system/config'
import { listPendingAction } from '@/api/wms/pendingAction'
import { getCoilStatisticsList } from "@/api/wms/coil";

export default {
  name: "Bonus",
  components: {
    BonusConfig,
    PostCoeffConfig,
    BonusTemplateManagement
  },
  data() {
    return {
      loading: true,
      detailLoading: false,
      buttonLoading: false,
      ids: [],
      showSearch: true,
      total: 0,
      bonusPoolList: [],
      title: "",
      open: false,
      detailOpen: false,
      currentPoolId: null,
      totalWeight: null,
      queryLoading: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productionLine: null,
        bonusTime: null,
        // createBy: this.$store.getters.name,
      },
      maxAdjustCoeff: 10.0,
      form: {},
      bonusPoolDetail: {},
      rules: {
        productionLine: [
          { required: true, message: "产线不能为空", trigger: "blur" }
        ],
        bonusTime: [
          { required: true, message: "奖金时间不能为空", trigger: "change" }
        ],
        bonusStartTime: [
          { required: true, message: "开始时间不能为空", trigger: "change" }
        ],
        bonusEndTime: [
          { required: true, message: "结束时间不能为空", trigger: "change" }
        ],
        totalBonus: [
          { required: true, message: "总金额不能为空", trigger: "blur" }
        ]
      },
      postCoeffConfigOpen: false,
      productionLineList: [
        {
          label: '酸轧线',
          value: '酸轧线',
          actions: '11,200,520'
        },
        {
          label: '镀锌线',
          value: '镀锌线',
          actions: '206,501,521'
        },
        {
          label: '拉矫线',
          value: '拉矫线',
          actions: '204,503,523'
        },
        {
          label: '双机架',
          value: '双机架',
          actions: '205,504,524'
        },
        {
          label: '镀铬线',
          value: '镀铬线',
          actions: '206,505,525'
        },
        {
          label: '脱脂线',
          value: '脱脂线',
          actions: '203,502,522'
        },
      ],
      templateManagementOpen: false,
    };
  },
  // computed: {
  //   currentUserName() {
  //     console.log(this.$store.getters.name, '计算属性');
  //     return this.$store.getters.name;
  //   }
  // },
  created() {
    this.getList();
    this.getMaxAdjustCoeff();
  },
  methods: {
    getList() {
      this.loading = true;
      listBonusPool(this.queryParams).then(response => {
        this.bonusPoolList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    getMaxAdjustCoeff() {
      getConfigKey('hrm.bonus.maxAdjust').then(res => {
        this.maxAdjustCoeff = Number(res.msg);
      })
    },

    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.totalWeight = null;
      this.form = {
        poolId: null,
        productionLine: null,
        bonusTime: null,
        totalBonus: 0,
        remark: null,
        // createBy: this.$store.getters.name,
        createTime: null,
        updateTime: null,
        delFlag: null,
        coeff: null
      };
      this.resetForm("form");
    },
    async queryCoilWeight() {
      this.queryLoading = true;
      try {
        const productionLines = this.form.productionLine.split(',');

        // 从productionLineList中获取productionLines对应的actions
        const productionLineActions = productionLines.map(line => this.productionLineList.find(item => item.value === line).actions);
        const pendingActions = await listPendingAction({
          startTime: this.form.bonusStartTime + ' 00:00:00',
          endTime: this.form.bonusEndTime + ' 23:59:59',
          actionTypes: productionLineActions.join(','),
          pageNum: 1,
          pageSize: 1000000,
        })
        const coilIds = pendingActions.rows.map(item => item.processedCoilIds);
        const coilStatistics = await getCoilStatisticsList({
          coilIds: coilIds.join(','),
        })
        this.totalWeight = coilStatistics.data.total_net_weight;
        this.calculateTotalBonus();
        this.queryLoading = false;
      } catch (error) {
        this.$modal.msgError(error.message);
        this.queryLoading = false;
      }
    },
    calculateTotalBonus() {
      if (this.totalWeight && this.form.coeff) {
        this.form.totalBonus = (this.totalWeight * this.form.coeff).toFixed(2);
      }
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.poolId);
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加奖金池";
    },
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      getBonusPool(row.poolId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改奖金池";
      });
    },
    handleDetail(row) {
      this.bonusPoolDetail = row;
      this.currentPoolId = row.poolId;
      this.detailOpen = true;
      this.$nextTick(() => {
        if (this.$refs.bonusConfigRef) {
          this.$refs.bonusConfigRef.refresh();
        }
      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.poolId != null) {
            updateBonusPool(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addBonusPool(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    handleDelete(row) {
      this.$modal.confirm('是否确认删除奖金池编号为"' + row.poolId + '"的数据项？').then(() => {
        return delBonusPool(row.poolId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    handlePostCoeffConfig() {
      this.postCoeffConfigOpen = true;
    },
    handleTemplateManagement() {
      this.templateManagementOpen = true;
    }
  }
};
</script>