<template>
  <div class="app-container">
    <el-form :model="queryParams" @submit.native.prevent ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <!-- <el-form-item label="班组类型" prop="calendarType">
        <el-select v-model="queryParams.calendarType" placeholder="请选择班组类型">
          <el-option
            v-for="dict in dict.type.mes_calendar_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item :label="$t('计划编号')" prop="planCode">
        <el-input
          v-model="queryParams.planCode"
          :placeholder="$t('请输入计划编号')"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('计划名称')" prop="planName">
        <el-input
          v-model="queryParams.planName"
          :placeholder="$t('请输入计划名称')"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('common.start_date')" prop="startDate">
        <el-date-picker clearable
          v-model="queryParams.startDate"
          type="date"
          value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item :label="$t('common.end_date')" prop="endDate">
        <el-date-picker clearable
          v-model="queryParams.endDate"
          type="date"
          value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t('common.search') }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('common.reset') }}</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"
          v-hasPermi="['mes:cal:calplan:add']"
        >{{ $t('common.add') }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['mes:cal:calplan:remove']"
        >{{ $t('common.del') }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['mes:cal:calplan:export']"
        >{{ $t('common.export') }}</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="calplanList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column :label="$t('计划编号')" align="center" prop="planCode" >
          <template slot-scope="scope">
                <el-button
                  type="text"
                  @click="handleView(scope.row)"
                  v-hasPermi="['mes:cal:calplan:query']"
                >{{scope.row.planCode}}</el-button>
          </template>
      </el-table-column>
      <el-table-column :label="$t('计划名称')" width="200px" align="center" prop="planName" :show-overflow-tooltip="true"/>
      <!-- <el-table-column label="班组类型" align="center" prop="calendarType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_calendar_type" :value="scope.row.calendarType"/>
        </template>
      </el-table-column> -->
      <el-table-column :label="$t('common.start_date')" align="center" prop="startDate" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('common.end_date')" align="center" prop="endDate" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('轮班方式')" align="center" prop="shiftType" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_shift_type" :value="scope.row.shiftType"/>
        </template>
      </el-table-column>
      <el-table-column :label="$t('单据状态')" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_order_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column :label="$t('common.option')" align="center" class-name="small-padding fixed-width" >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="scope.row.status =='PREPARE'"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['mes:cal:calplan:edit']"
          >{{ $t('common.edit') }}</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            v-if="scope.row.status =='PREPARE'"
            @click="handleDelete(scope.row)"
            v-hasPermi="['mes:cal:calplan:remove']"
          >{{ $t('common.del') }}</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" v-loading="formLoading" :visible.sync="open" width="960px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('计划编号')" prop="planCode">
              <div style="display:flex;align-items: center;">
                <el-input v-model="form.planCode" disabled :placeholder="$t('请输入计划编号')" />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('计划名称')" prop="planName">
              <el-input v-model="form.planName" :placeholder="$t('请输入计划名称')" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('common.start_date')" prop="startDate">
              <el-date-picker clearable
                v-model="form.startDate"
                type="date"
                style="width: 100%;"
                value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('common.end_date')" prop="endDate">
              <el-date-picker clearable
                v-model="form.endDate"
                type="date"
                style="width: 100%;"
                value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item :label="$t('轮班方式')">
              <el-radio-group v-model="form.shiftType"
                    :disabled="optType === 'view'">
                <el-radio
                  v-for="dict in dict.type.mes_shift_type"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item :label="$t('周六是否上班')">
              <el-radio-group v-model="form.saturday">
                <el-radio :label="1">{{$t('是')}}</el-radio>
                <el-radio :label="2">{{$t('否')}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item :label="$t('周日是否上班')">
              <el-radio-group v-model="form.sunday">
                <el-radio :label="1">{{$t('是')}}</el-radio>
                <el-radio :label="2">{{$t('否')}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('common.remark')" prop="remark">
              <el-input v-model="form.remark" type="textarea" :placeholder="$t('请输入内容')" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-tabs type="border-card">
        <el-tab-pane :label="$t('班次')">
          <Shift v-if="open" ref="shiftTab" :planId="form.planId" :shiftType="form.shiftType" :optType="optType"></Shift>
        </el-tab-pane>
        <el-tab-pane v-if="open" :label="$t('common.workunit')">
          <Team v-if="open" ref="teamTab" :planId="form.planId" :planCode="form.planCode" :form="form" :calendarType="form.calendarType" :optType="optType"></Team>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancel" v-if="optType =='view' || form.status !='PREPARE'">{{ $t('common.back') }}</el-button>
        <el-button type="primary" @click="submitForm" v-if="form.status =='PREPARE' && optType !='view' ">{{ $t('common.confirm') }}</el-button>
        <el-button type="success" @click="handleFinish" v-if="form.status =='PREPARE' && optType !='view'  && form.planId !=null">{{$t('完成')}}</el-button>
        <el-button @click="cancel">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>


import { listCalplan, getCalplan, delCalplan, addCalplan, updateCalplan, finishCalplan } from "@/api/mes/cal/calplan";
import Shift from "./shift";
import Team  from "./team";
import {genCode} from "@/api/system/autocode/rule"
export default {
  name: "Calplan",
  dicts: ['mes_shift_method','mes_shift_type','mes_calendar_type','mes_order_status'],
  components: {Shift,Team},
  data() {
    return {
      //自动生成编码
      autoGenFlag:false,
      optType: undefined,
      // 遮罩层
      loading: true,
      formLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 排班计划表格数据
      calplanList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        planCode: null,
        planName: null,
        calendarType:null,
        startDate: null,
        endDate: null,
        shiftType: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        planCode: [
          { required: true, message: this.$t('计划编号不能为空'), trigger: "blur" }
        ],
        planName: [
          { required: true, message: this.$t('计划名称不能为空'), trigger: "blur" }
        ],
        calendarType:[
          { required: true, message: this.$t('请选择班组类型'), trigger: "blur" }
        ],
        startDate: [
          { required: true, message: this.$t('开始日期不能为空'), trigger: "blur" }
        ],
        endDate: [
          { required: true, message: this.$t('结束日期不能为空'), trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询排班计划列表 */
    getList() {
      this.loading = true;
      listCalplan(this.queryParams).then(response => {
        this.calplanList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        planId: null,
        planCode: null,
        planName: null,
        calendarType:null,
        startDate: null,
        endDate: null,
        shiftType: '',
        status: "",
        remark: null,
        saturday: null,
        sunday: 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.planId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.shiftType = 'SINGLE'
      this.form.status = "PREPARE"
      this.form.saturday = 2
      this.form.sunday = 2
      this.open = true;
      this.title = this.$t('添加排班计划');
      this.handleAutoGenChange()
      this.optType = "add";
    },
    // 查询明细按钮操作
    handleView(row){
      this.reset();
      const planId = row.planId || this.ids
      getCalplan(planId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = this.$t('查看排班计划');
        this.optType = "view";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const planId = row.planId || this.ids
      getCalplan(planId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = this.$t('修改排班计划');
        this.optType = "edit";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.planId != null) {
            let params = Object.assign({}, this.form)
            params.calShifts = this.$refs.shiftTab.shiftList
            params.calWorkunits = this.$refs.teamTab.teamList
            updateCalplan(params).then(response => {
              this.$modal.msgSuccess(this.$t('common.edit_success'));
              this.open = false;
              this.getList();
            });
          } else {
            let params = Object.assign({}, this.form)
            params.calShifts = this.$refs.shiftTab.shiftList
            params.calWorkunits = this.$refs.teamTab.teamList
            addCalplan(params).then(response => {
              this.$modal.msgSuccess(this.$t('common.add_success'));
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const planIds = row.planId || this.ids;
      this.$modal.confirm(this.$t('common.confirm_del_data')).then(function() {
        return delCalplan(planIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(this.$t('common.del_success'));
      }).catch(() => {});
    },
    handleFinish(){
      this.$modal.confirm(this.$t('是否完成计划编制？【完成后将不能更改】')).then(()=>{
        this.form.status = 'CONFIRMED';
        this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.planId != null) {
            let params = Object.assign({}, this.form)
            params.calShifts = this.$refs.shiftTab.shiftList
            params.calWorkunits = this.$refs.teamTab.teamList
            finishCalplan(params).then(response => {
              this.$modal.msgSuccess(this.$t('已完成'));
              this.open = false;
              this.getList();
              this.formLoading = false;
            },err =>{
              this.form.status = 'PREPARE';
              this.formLoading = false;
            });
          }
        }
      });
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('cal/calplan/export', {
        ...this.queryParams
      }, `calplan_${new Date().getTime()}.xlsx`)
    },
    //自动生成编码
    handleAutoGenChange(){
      genCode('CAL_PLAN_CODE').then(response =>{
        this.form.planCode = response;
      });
    },
  }
};
</script>
