<template>
  <section class="content" style="margin-top: -18px;">
    <div class="box box-info">
      <!-- 头信息 -->
      <div
        class="box-header with-border"
        style="background-color:#d3dce6;margin-bottom:20px;"
      >
        <h3 class="box-title">项目统计</h3>
        <div class="box-tools pull-right">
          <button type="button" class="btn btn-box-tool" data-widget="collapse">
            <i class="fa fa-minus"></i>
          </button>
        </div>
      </div>

      <!-- 正文信息 -->
      <div class="box-body">
        <el-form
          :model="formSearch"
          :inline="true"
          label-position="right"
          label-width="100px"
        >
          <el-form-item label="学校">
            <el-select
              :disabled="showGoBack"
              v-model="formSearch.orgId"
              placeholder="请选择"
              filterable
              clearable
              @change="searchExamList(formSearch.orgId);"
            >
              <el-option
                v-for="item in orgList"
                :label="item.orgName"
                :value="item.orgId"
                :key="item.orgId"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="考试">
            <el-select
              :disabled="showGoBack"
              v-model="formSearch.examId"
              @change="searchRecords"
              placeholder="请选择"
            >
              <el-option
                v-for="item in examList"
                :label="item.examName"
                :value="item.examId"
                :key="item.examId"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button
              size="small"
              type="primary"
              icon="el-icon-search"
              @click="searchRecords"
              >查询
            </el-button>

            <el-button
              size="small"
              type="primary"
              icon="el-icon-plus"
              :disabled="!hasPermit"
              v-show="formSearch.examId != ''"
              @click="openOtherSettingDialog"
              >新增其它事项
            </el-button>

            <el-button
              size="small"
              type="primary"
              icon="el-icon-refresh"
              :disabled="!hasPermit"
              v-show="formSearch.examId != ''"
              @click="refreshStatistic"
              >刷新
            </el-button>

            <el-button
              size="small"
              type="primary"
              icon="el-icon-arrow-left"
              v-show="showGoBack"
              @click="goBack"
              >返回
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 数据列表 -->
        <el-table
          v-loading="loading"
          :data="tableData"
          element-loading-text="数据加载中"
          style="width:100%;"
          border
        >
          <el-table-column width="60" label="类型" prop="type" />
          <el-table-column width="80" label="人科次" prop="totalStudent" />
          <el-table-column width="100" label="课程数量" prop="totalCourse" />
          <el-table-column width="100" label="试卷数量" prop="totalPaper" />
          <el-table-column width="100" label="印刷数量A3" prop="A3" />
          <el-table-column width="100" label="印刷数量A4" prop="A4" />
          <el-table-column width="100" label="总数(A3)" prop="sumA3" />
          <el-table-column width="80" label="试卷袋数" prop="totalPkg" />
          <el-table-column label="事项说明" prop="remark" />
          <el-table-column width="120" label="印刷供应商" prop="supplierName" />
          <el-table-column width="120" label="项目经理" prop="pmName" />

          <el-table-column width="180" label="操作" :context="_self">
            <template slot-scope="scope">
              <el-button
                size="mini"
                icon="el-icon-menu"
                v-if="scope.row.btnType == 'BACKUP'"
                @click="openBackupSettingDialog"
                :disabled="!hasPermit"
                >备份设置
              </el-button>

              <el-button
                size="mini"
                icon="el-icon-edit"
                v-if="scope.row.btnType == 'OTHER'"
                @click="openOtherSettingDialog(scope.row);"
                :disabled="!hasPermit"
                >修改
              </el-button>

              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                v-if="scope.row.btnType == 'OTHER'"
                @click="removeOtherSetting(scope.row);"
                :disabled="!hasPermit"
                >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 备份设置弹窗 -->
      <el-dialog
        title="备份设置"
        width="500px"
        :visible.sync="backupSettingDialog"
        @close="closeBackupSettingDialog"
      >
        <el-form
          :model="backupSettingForm"
          ref="backupSettingForm"
          :rules="rules"
          label-position="right"
          label-width="80px"
        >
          <el-tabs v-model="eachPkgTab">
            <el-tab-pane name="first">
              <span slot="label"
                >每袋冗余设置
                <el-switch v-model="backupSettingForm.needEachPkg"></el-switch
              ></span>
              <el-form-item label="比例" prop="eachPkgPercent">
                <el-input
                  v-model="backupSettingForm.eachPkgPercent"
                  :disabled="!backupSettingForm.needEachPkg"
                  ><template slot="append"
                    >%</template
                  ></el-input
                >
              </el-form-item>
              <el-form-item label="最大" prop="eachPkgMax">
                <el-input
                  v-model="backupSettingForm.eachPkgMax"
                  :disabled="!backupSettingForm.needEachPkg"
                  ><template slot="append"
                    >%</template
                  ></el-input
                >
              </el-form-item>
              <el-form-item label="最小" prop="eachPkgMin">
                <el-input
                  v-model="backupSettingForm.eachPkgMin"
                  :disabled="!backupSettingForm.needEachPkg"
                  ><template slot="append"
                    >%</template
                  ></el-input
                >
              </el-form-item>
            </el-tab-pane>
          </el-tabs>

          <el-tabs v-model="alonePkgTab">
            <el-tab-pane name="first">
              <span slot="label"
                >单独备份袋设置
                <el-switch v-model="backupSettingForm.needAlonePkg"></el-switch
              ></span>
              <el-form-item label="归集参数" prop="groupType">
                <el-select
                  v-model="backupSettingForm.groupType"
                  :disabled="!backupSettingForm.needAlonePkg"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in groupTypeList"
                    :label="item.label"
                    :value="item.value"
                    :key="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="比例" prop="alonePkgPercent">
                <el-input
                  v-model="backupSettingForm.alonePkgPercent"
                  :disabled="!backupSettingForm.needAlonePkg"
                  ><template slot="append"
                    >%</template
                  >
                </el-input>
              </el-form-item>
              <el-form-item label="最大" prop="alonePkgMax">
                <el-input
                  v-model="backupSettingForm.alonePkgMax"
                  :disabled="!backupSettingForm.needAlonePkg"
                  ><template slot="append"
                    >%</template
                  ></el-input
                >
              </el-form-item>
              <el-form-item label="最小" prop="alonePkgMin">
                <el-input
                  v-model="backupSettingForm.alonePkgMin"
                  :disabled="!backupSettingForm.needAlonePkg"
                  ><template slot="append"
                    >%</template
                  ></el-input
                >
              </el-form-item>
            </el-tab-pane>
          </el-tabs>
        </el-form>
        <div style="text-align: center;">
          <el-button type="primary" @click="editBackupSetting"
            >确 定
          </el-button>
          <el-button @click="closeBackupSettingDialog">取 消</el-button>
        </div>
      </el-dialog>

      <!-- 其它事项弹窗 -->
      <el-dialog
        title="其它事项"
        width="750px"
        :visible.sync="otherSettingDialog"
        @close="closeOtherSettingDialog"
      >
        <el-form
          :model="otherSettingForm"
          ref="otherSettingForm"
          :rules="rules"
          label-position="right"
          label-width="110px"
        >
          <el-form-item label="事项内容" prop="remark">
            <el-input
              type="textarea"
              :rows="8"
              v-model="otherSettingForm.remark"
            ></el-input>
          </el-form-item>
        </el-form>
        <div style="text-align: center">
          <el-button type="primary" @click="editOtherSetting">确 定 </el-button>
          <el-button @click="closeOtherSettingDialog">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </section>
</template>

<script>
import { PRINT_API } from "@/constants/constants";
import { userRole, groupTypeList } from "../constants/constants.js";
import { mapState } from "vuex";

export default {
  data() {
    let validateEachPkgPercent = (rule, value, callback) => {
      if (this.backupSettingForm.needEachPkg) {
        if (this.isEmptyNumber(this.backupSettingForm.eachPkgPercent)) {
          callback(new Error("请输入正确的数值！"));
          return;
        }
      }
      callback();
    };

    let validateEachPkgMax = (rule, value, callback) => {
      if (this.backupSettingForm.needEachPkg) {
        if (this.isEmptyNumber(this.backupSettingForm.eachPkgMax)) {
          callback(new Error("请输入正确的数值！"));
          return;
        }
      }
      callback();
    };

    let validateEachPkgMin = (rule, value, callback) => {
      if (this.backupSettingForm.needEachPkg) {
        if (this.isEmptyNumber(this.backupSettingForm.eachPkgMin)) {
          callback(new Error("请输入正确的数值！"));
          return;
        }
      }
      callback();
    };

    let validateAlonePkgPercent = (rule, value, callback) => {
      if (this.backupSettingForm.needAlonePkg) {
        if (this.isEmptyNumber(this.backupSettingForm.alonePkgPercent)) {
          callback(new Error("请输入正确的数值！"));
          return;
        }
      }
      callback();
    };

    let validateAlonePkgMax = (rule, value, callback) => {
      if (this.backupSettingForm.needAlonePkg) {
        if (this.isEmptyNumber(this.backupSettingForm.alonePkgMax)) {
          callback(new Error("请输入正确的数值！"));
          return;
        }
      }
      callback();
    };

    let validateAlonePkgMin = (rule, value, callback) => {
      if (this.backupSettingForm.needAlonePkg) {
        if (this.isEmptyNumber(this.backupSettingForm.alonePkgMin)) {
          callback(new Error("请输入正确的数值！"));
          return;
        }
      }
      callback();
    };

    let validateGroupType = (rule, value, callback) => {
      if (this.backupSettingForm.needAlonePkg) {
        if (this.isEmptyStr(this.backupSettingForm.groupType)) {
          callback(new Error("请选择归集参数！"));
          return;
        }
      }
      callback();
    };

    return {
      formSearch: {
        orgId: "",
        examId: ""
      },
      curUserRole: userRole,
      groupTypeList: groupTypeList,
      hasPermit: false,
      loading: false,
      showGoBack: false,
      tableData: [],
      projectId: "",
      eachPkgTab: "first",
      alonePkgTab: "first",
      orgList: [],
      examList: [],
      backupSettingDialog: false,
      backupSettingForm: {
        projectId: "",
        needAlonePkg: true,
        needEachPkg: true,
        eachPkgPercent: "",
        eachPkgMax: "",
        eachPkgMin: "",
        alonePkgPercent: "",
        alonePkgMax: "",
        alonePkgMin: "",
        groupType: ""
      },
      otherSettingDialog: false,
      otherSettingForm: {
        id: "",
        projectId: "",
        remark: ""
      },
      rules: {
        eachPkgPercent: [
          {
            type: "number",
            required: true,
            validator: validateEachPkgPercent,
            trigger: "change"
          }
        ],
        eachPkgMax: [
          {
            type: "number",
            required: true,
            validator: validateEachPkgMax,
            trigger: "change"
          }
        ],
        eachPkgMin: [
          {
            type: "number",
            required: true,
            validator: validateEachPkgMin,
            trigger: "change"
          }
        ],
        alonePkgPercent: [
          {
            type: "number",
            required: true,
            validator: validateAlonePkgPercent,
            trigger: "change"
          }
        ],
        alonePkgMax: [
          {
            type: "number",
            required: true,
            validator: validateAlonePkgMax,
            trigger: "change"
          }
        ],
        alonePkgMin: [
          {
            type: "number",
            required: true,
            validator: validateAlonePkgMin,
            trigger: "change"
          }
        ],
        groupType: [
          { required: true, validator: validateGroupType, trigger: "change" }
        ],
        remark: [
          { required: true, message: "请输入事项内容！", trigger: "change" }
        ]
      }
    };
  },
  methods: {
    searchRecords() {
      /* 查询记录列表 */
      let orgId = this.formSearch.orgId;
      if (this.isEmptyNumber(orgId)) {
        this.$notify({
          message: "请选择学校！",
          type: "warning"
        });
        return;
      }

      let examId = this.formSearch.examId;
      if (this.isEmptyNumber(examId)) {
        this.$notify({
          message: "请选择考试！",
          type: "warning"
        });
        return;
      }

      this.loading = true;
      let url =
        PRINT_API + "/printing/project/statistic/" + orgId + "/" + examId;

      this.$http.post(url, this.formSearch).then(
        response => {
          this.tableData = [];
          this.projectId = response.data.projectId;
          this.renderTableColumns(response.data);
          this.loadOtherSetting(this.projectId);
          this.loading = false;
        },
        error => {
          console.log(error);
          this.loading = false;
        }
      );
    },
    renderTableColumns(data) {
      let normalColumn = {
        type: "常规",
        A3: data.normalA3,
        A4: data.normalA4,
        sumA3: data.summary,
        totalStudent: data.totalStudent,
        totalCourse: data.totalCourse,
        totalPaper: data.totalPaper,
        totalPkg: data.totalPkg,
        supplierName: data.supplierName,
        pmName: data.pmName
      };
      this.tableData.push(normalColumn);

      let backupColumn = {
        type: "备份",
        A3: data.backupA3,
        A4: data.backupA4,
        sumA3: data.backupSummary,
        btnType: "BACKUP"
      };
      this.tableData.push(backupColumn);

      let totalColumn = {
        type: "合计",
        A3: data.totalA3,
        A4: data.totalA4,
        sumA3: data.totalSummary
      };
      this.tableData.push(totalColumn);
    },
    searchExamList(orgId) {
      /* 查询考试列表 */
      this.formSearch.examId = "";
      this.examList = [];
      this.tableData = [];
      this.projectId = "";
      //console.log("orgId:" + orgId);
      if (!this.isEmptyNumber(orgId)) {
        let url = PRINT_API + "/printing/project/exam/list?orgId=" + orgId;
        this.$http.post(url).then(response => {
          this.examList = response.data;
        });
      }
    },
    refreshStatistic() {
      /* 刷新当前统计信息 */
      let orgId = this.formSearch.orgId;
      if (this.isEmptyNumber(orgId)) {
        this.$notify({
          message: "请选择学校！",
          type: "warning"
        });
        return;
      }

      let examId = this.formSearch.examId;
      if (this.isEmptyNumber(examId)) {
        this.$notify({
          message: "请选择考试！",
          type: "warning"
        });
        return;
      }

      this.$confirm("刷新当前统计信息？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let url =
            PRINT_API +
            "/printing/project/statistic/refresh/" +
            orgId +
            "/" +
            examId;
          this.$http.post(url).then(
            () => {
              this.$notify({
                type: "success",
                message: "刷新成功！"
              });
              this.searchRecords();
            },
            () => {
              this.$notify({
                type: "error",
                message: "刷新失败！"
              });
            }
          );
        })
        .catch(() => {
          //ignore
        });
    },
    editBackupSetting() {
      /* 保存备份设置 */
      this.$refs.backupSettingForm.validate(valid => {
        if (!valid) {
          return false;
        }

        if (
          !this.backupSettingForm.needEachPkg &&
          !this.backupSettingForm.needAlonePkg
        ) {
          this.$notify({
            message: "请至少设置一种备份方式！",
            type: "warning"
          });
          return;
        }

        let url = PRINT_API + "/project/backup/setting/save";
        this.$http.post(url, this.backupSettingForm).then(
          () => {
            this.$notify({
              type: "success",
              message: "保存备份设置成功！"
            });
            this.backupSettingDialog = false;
          },
          error => {
            console.log(error);
            this.$notify({
              message: "保存备份设置失败！",
              type: "error"
            });
          }
        );
      });
    },
    openBackupSettingDialog() {
      /* 打开备份设置弹窗 */
      let url = PRINT_API + "/project/backup/setting/" + this.projectId;
      this.$http.post(url).then(
        response => {
          this.backupSettingForm = response.data;
        },
        () => {
          this.backupSettingForm = {
            projectId: this.projectId,
            needAlonePkg: true,
            needEachPkg: true,
            eachPkgPercent: "",
            eachPkgMax: "",
            eachPkgMin: "",
            alonePkgPercent: "",
            alonePkgMax: "",
            alonePkgMin: "",
            groupType: ""
          };
        }
      );
      this.backupSettingDialog = true;
    },
    closeBackupSettingDialog() {
      /* 关闭备份设置弹窗 */
      this.backupSettingDialog = false;
    },
    loadOtherSetting(projectId) {
      /* 查询其它事项列表 */
      let url =
        PRINT_API + "/project/other/setting/list?projectId=" + projectId;

      this.$http.post(url).then(
        response => {
          let list = response.data;
          if (!list || list.length < 1) {
            return;
          }
          for (let obj of list) {
            obj.type = "其它";
            obj.btnType = "OTHER";
            this.tableData.push(obj);
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    editOtherSetting() {
      /* 保存其它事项 */
      this.$refs.otherSettingForm.validate(valid => {
        if (!valid) {
          return false;
        }
        let url = PRINT_API + "/project/other/setting/save";
        this.$http.post(url, this.otherSettingForm).then(
          () => {
            this.$notify({
              type: "success",
              message: "保存其它事项成功！"
            });
            this.otherSettingDialog = false;
            this.searchRecords();
          },
          error => {
            console.log(error);
            this.$notify({
              message: "保存其它事项失败！",
              type: "error"
            });
          }
        );
      });
    },
    removeOtherSetting(row) {
      /* 删除某个其它事项 */
      this.$confirm("确定删除当前事项吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          var url = PRINT_API + "/project/other/setting/delete/" + row.id;
          this.$http.post(url).then(
            () => {
              this.$notify({
                type: "success",
                message: "删除当前事项成功！"
              });
              this.searchRecords();
            },
            () => {
              this.$notify({
                type: "error",
                message: "删除当前事项失败！"
              });
            }
          );
        })
        .catch(() => {
          /*ignore*/
        });
    },
    openOtherSettingDialog(row) {
      /* 打开其它事项弹窗 */
      if (this.isEmptyNumber(this.projectId)) {
        this.$notify({
          message: "请选择学校和考试！",
          type: "warning"
        });
        return;
      }
      this.otherSettingDialog = true;
      this.otherSettingForm.projectId = this.projectId;
      if (row.id) {
        this.otherSettingForm.id = row.id;
      } else {
        this.otherSettingForm.id = "";
      }
      if (row.remark) {
        this.otherSettingForm.remark = row.remark;
      } else {
        this.otherSettingForm.remark = "";
      }
    },
    closeOtherSettingDialog() {
      /* 关闭其它事项弹窗 */
      this.otherSettingDialog = false;
    },
    goBack() {
      /* 返回上级界面 */
      this.$router.push({ path: "/print/project/list" });
    }
  },
  computed: {
    ...mapState({ user: state => state.user })
  },
  created() {
    this.loadOrgList();

    this.loadUserRole(this.user);

    if (this.curUserRole.isSuperLeader || this.curUserRole.isPM) {
      this.hasPermit = true;
    } else {
      this.hasPermit = false;
    }

    /* 加载默认数据 */
    let orgId = this.$route.params.orgId;
    let examId = this.$route.params.examId;
    if (orgId != "0" || examId != "0") {
      this.searchExamList(orgId);
      this.showGoBack = true;
      this.formSearch.orgId = parseInt(orgId);
      this.formSearch.examId = parseInt(examId);
      this.searchRecords();
    }
  }
};
</script>

<style scoped>
.page {
  margin-top: 10px;
}
.pull-right {
  float: right;
}
.pull-left {
  float: left;
}
</style>
