<template>
  <div class="app-container">

    <div class="company" v-if="!$store.state.user.tenantId">
      <el-input
        style="width: 200px"
        placeholder="公司名称"
        size="small"
        prefix-icon="el-icon-search"
        v-model="gsInfo.tenantName"
        @keyup.enter.native="getGsInfoList">
      </el-input>
      <div class="cp-content" style="width: 200px">
        <div :class="gsInfo.active_id===item.id?'cp-item active':'cp-item'" @click="changCompany(item.id)" v-for="item in gsInfo.list">{{ item.name }}</div>
      </div>
    </div>

    <div :class="$store.state.user.tenantId?'content-all':'content'">

      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
        <el-form-item label="包活工单名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入包活工单名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="包活工单ID" prop="id">
          <el-input
            v-model="queryParams.id"
            placeholder="请输入包活工单ID"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <treeselect v-model="queryParams.deptId" :options="deptOptions" :show-count="true" placeholder="请选择归属部门" style="width: 220px"/>
        </el-form-item>
        <el-form-item label="员工" prop="empId">
          <el-select v-model="queryParams.empId" filterable clearable placeholder="请选择">
            <el-option
              v-for="item in employeeList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="车间" prop="workshop">
          <el-select v-model="queryParams.workshop" placeholder="请选择车间" clearable>
            <el-option
              v-for="dict in dict.type.pay_workshop"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="入库时间" prop="instorageTime">
          <el-date-picker clearable
                          v-model="queryParams.instorageTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择入库时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="入库月份" prop="instorageDate">
          <el-date-picker clearable
                          v-model="queryParams.instorageDate"
                          type="month"
                          value-format="yyyy-MM"
                          placeholder="请选择入库月份">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="工作日期" prop="workDate">
          <el-date-picker clearable
                          v-model="queryParams.workDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择工作时间">
          </el-date-picker>
        </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"
            v-hasPermi="['pay:workOrderBaohuo:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['pay:workOrderBaohuo:edit']"
          >修改</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="['pay:workOrderBaohuo:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-date-picker
            v-model="queform.date"
            type="month"
            size="mini"
            placeholder="选择年月"
            value-format="yyyy-MM">
          </el-date-picker>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleBaohuogs" v-hasPermi="['pay:workOrderBaohuo:sum']">查询员工总工时</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['pay:workOrderBaohuo:export']"
          >信息导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="workOrderBaohuoList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="工单ID" align="center" prop="id"/>
        <el-table-column label="包活工单名称" align="center" prop="name" />
        <el-table-column label="工作内容" align="center" prop="content" />
        <el-table-column label="质检人员" align="center" prop="qualityName" />
        <el-table-column label="检验说明" align="center" prop="qualityRemark" />
        <el-table-column label="入库时间" align="center" prop="instorageTime">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.instorageTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="入库人员" align="center" prop="instorageName" />
        <el-table-column label="实际入库数量" align="center" prop="instorageNum" />
        <el-table-column label="项目经理" align="center" prop="managerName" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['pay:workOrderBaohuo:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleDetails(scope.row)"
              v-hasPermi="['pay:workOrderBaohuo:query']"
            >详情</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['pay:workOrderBaohuo:remove']"
            >删除</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"
      />

    </div>

    <!-- 添加或修改包活派工单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body :close-on-click-modal="false">
      <div class="my-dialog1">
        <el-form ref="form" :model="form" :rules="rules" label-width="90px" v-if="title !== '包活派工单详情'">
          <el-card>
            <el-row>
              <el-col :span="6">
                <el-form-item label="部门" prop="deptId">
                  <treeselect class="depselect" v-model="form.deptId" :options="deptOptions" :show-count="true" placeholder="请选择归属部门" style="height: 30px;"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="车间" prop="workshop">
                  <el-select v-model="form.workshop" placeholder="请选择车间" clearable style="width:100%">
                    <el-option
                      v-for="dict in dict.type.pay_workshop"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="工单名称" prop="name">
                  <el-input v-model="form.name" placeholder="请输入包活工单名称" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="项目经理" prop="managerName">
                  <el-input v-model="form.managerName" placeholder="请输入项目经理" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="实际入库数量" prop="instorageNum" label-width="100px">
                  <el-input-number v-model="form.instorageNum" :min="0" :max="10000" style="width: 100%;"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="入库时间" prop="instorageTime">
                  <el-date-picker clearable style="width:100%"
                                  v-model="form.instorageTime"
                                  type="date"
                                  value-format="yyyy-MM-dd"
                                  placeholder="请选择入库日期">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="入库人员" prop="instorageName">
                  <el-input v-model="form.instorageName" placeholder="请输入入库人员" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="质检人员" prop="qualityName">
                  <el-input v-model="form.qualityName" placeholder="请输入质检人员" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="工作内容">
                  <el-input
                    type="textarea"
                    :rows="2"
                    placeholder="请输入工作内容"
                    v-model="form.content">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="检验说明" prop="qualityRemark">
                  <el-input v-model="form.qualityRemark" type="textarea" placeholder="请输入内容" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
          <el-card class="panel-group-top" style="margin-top: 10px;">
            <el-button size="mini" @click="addEmp" style="margin-bottom: 10px;">添加员工</el-button>
            <el-row v-for="(emp, index) in form.empList" :key="emp.key">
              <el-col :span="8">
                <el-form-item label="员工姓名" :prop="'empList.' + index + '.empName'" :rules="{required: true, message: '员工姓名不能为空', trigger: 'change'}">
                  <el-input placeholder="请选择员工姓名" readonly v-model="emp.empName" @focus="changeEmp(emp, index)">
                    <i slot="suffix" class="el-input__icon el-icon-search" style="color:#0f00d1; font-weight: bolder"></i>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="是否帮工" :prop="'empList.' + index + '.helper'">
                  <template>
                    <el-radio v-model="emp.helper" :label=0>否</el-radio>
                    <el-radio v-model="emp.helper" :label=1>是</el-radio>
                  </template>
                </el-form-item>
              </el-col>
              <el-col :span="2">
                <el-button size="mini" @click.prevent="removeEmp(emp)" style="margin-top: 8px">删除</el-button>
              </el-col>
            </el-row>
          </el-card>
          <el-card class="panel-group-top" style="margin-top: 10px;">
            <el-button size="mini" @click="addPro" style="margin-bottom: 10px;">新增产品</el-button>
            <el-row v-for="(pro, index) in form.prodList" :key="pro.key" style="border: 1px solid #eeeeee;padding-top: 10px;margin-top: 5px">
              <el-col :span="6">
                <el-form-item label="产品名称" :prop="'prodList.' + index + '.productName'" :rules="{required: true, message: '产品名称不能为空', trigger: 'change'}">
                  <el-input placeholder="请选择产品名称" readonly v-model="pro.productName" @focus="changeProduct(pro, index)">
                    <i slot="suffix" class="el-input__icon el-icon-search" style="color:#0f00d1; font-weight: bolder"></i>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="产品价格" label-width="80px">
                <div style="color: red; background: #eeeeee; padding: 0 2px; box-sizing: border-box;height: 35px;">
                  {{pro.minPrice !== null ? pro.minPrice+'元 - '+ pro.maxPrice+ '元' : null}}
                </div>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="产品规格" label-width="80px">
                  <el-input v-model="pro.productSpecification" placeholder="请输入产品规格" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="工序" label-width="55px">
                  <el-input v-model="pro.process" placeholder="请输入工序" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="加工数量" :prop="'prodList.' + index + '.productNum'" :rules="{required: true, validator: validator, trigger: 'change'}">
                  <el-input-number v-model="pro.productNum" :min="0" :max="10000" style="width: 100%;" @change="changeProductNum(index)"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="原材料" label-width="80px">
                  <el-input v-model="pro.productMaterial" placeholder="请输入原材料" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="单位" label-width="80px" :prop="'prodList.' + index + '.unit'">
                  <el-input v-model="pro.unit" placeholder="请输入单位" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="单价" label-width="55px" :prop="'prodList.' + index + '.price'" :rules="{ required: true, message: '单价不能为空', trigger: 'blur' }">
                  <el-input v-model="pro.price" placeholder="请输入单价" oninput ="value=value.replace(/[^0-9.]/g,'')" @input="inputProductNum(index)" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="总金额" :prop="'prodList.' + index + '.amount'" :rules="{ required:true, message: '总金额不能为空', trigger: 'blur' }">
                  <el-input v-model="pro.amount" placeholder="请输入加工总金额" oninput ="value=value.replace(/[^0-9.]/g,'')"/>
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-button size="mini" @click.prevent="removePro(pro)" style="margin-left: 10px;">删除</el-button>
              </el-col>
            </el-row>
          </el-card>
          <el-card class="panel-group-top" style="margin-top: 10px;">
            <el-button size="mini" @click="addWork" style="margin-bottom: 10px;">新增时间段</el-button>
            <el-row v-for="(work, index) in form.worktimeList" :key="work.key">
              <el-col :span="6">
                <el-form-item
                  label="干活日期"
                  :prop="'worktimeList.' + index + '.date'"
                  :rules="{required: true, message: '干活日期不能为空', trigger: 'blur'}">
                  <el-date-picker
                    v-model="work.date"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="选择干活日期" style="width: 100%">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item
                  label="开始时间"
                  :prop="'worktimeList.' + index + '.beginTime'"
                  :rules="{required: true, message: '开始时间不能为空', trigger: 'blur'}">
                  <el-time-picker v-model="work.beginTime" placeholder="开始时间" value-format="HH:mm" format="HH:mm" style="width: 145px;"></el-time-picker>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item
                  label="结束时间"
                  :prop="'worktimeList.' + index + '.endTime'"
                  :rules="{required: true, message: '结束时间不能为空', trigger: 'blur'}">
                  <el-time-picker v-model="work.endTime" value-format="HH:mm" format="HH:mm" placeholder="结束时间" style="width: 145px;"></el-time-picker>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item
                  label="有效时长"
                  :prop="'worktimeList.' + index + '.validHours'"
                  :rules="{required: true, message: '有效时长不能为空', trigger: 'blur'}">
                  <el-input v-model="work.validHours" placeholder="请输入有效工作时长" />
                </el-form-item>
              </el-col>
              <el-col :span="3" style="display: flex;justify-content: end">
                <el-button size="mini" @click.prevent="removeWork(work)">删除</el-button>
              </el-col>
            </el-row>
          </el-card>
          <el-card class="panel-group-top" style="margin-top: 10px;">
            <el-row>
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input
                    type="textarea"
                    :rows="2"
                    placeholder="请输入备注"
                    v-model="form.remark">
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
        </el-form>
        <el-form ref="form" :model="form" :rules="rules" label-width="90px" v-if="title === '包活派工单详情'">
          <el-card>
            <el-row>
              <el-col :span="6">
                <el-form-item label="部门" prop="deptId">
                  <treeselect disabled class="depselect" v-model="form.deptId" :options="deptOptions" :show-count="true" placeholder="请选择归属部门" style="height: 30px;"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="车间" prop="workshop">
                  <el-select v-model="form.workshop" placeholder="请选择车间" clearable style="width:100%" disabled>
                    <el-option
                      v-for="dict in dict.type.pay_workshop"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="工单名称" prop="name">
                  <el-input v-model="form.name" placeholder="请输入包活工单名称" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="项目经理" prop="managerName">
                  <el-input v-model="form.managerName" placeholder="请输入项目经理" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="实际入库数量" prop="instorageNum" label-width="100px">
                  <el-input-number v-model="form.instorageNum" :min="0" :max="10000" style="width: 100%;" disabled></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="入库时间" prop="instorageTime">
                  <el-date-picker clearable style="width:100%" disabled
                                  v-model="form.instorageTime"
                                  type="date"
                                  value-format="yyyy-MM-dd"
                                  placeholder="请选择入库日期">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="入库人员" prop="instorageName">
                  <el-input v-model="form.instorageName" placeholder="请输入入库人员" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="质检人员" prop="qualityName">
                  <el-input v-model="form.qualityName" placeholder="请输入质检人员" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="工作内容">
                  <el-input disabled
                    type="textarea"
                    :rows="2"
                    placeholder="请输入工作内容"
                    v-model="form.content">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="检验说明" prop="qualityRemark">
                  <el-input v-model="form.qualityRemark" type="textarea" placeholder="请输入内容" disabled/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
          <el-card class="panel-group-top" style="margin-top: 10px;">
            <el-row v-for="(emp, index) in form.empList" :key="emp.key">
              <el-col :span="8">
                <el-form-item label="员工姓名" :prop="'empList.' + index + '.empName'" :rules="{required: true, message: '员工姓名不能为空', trigger: 'change'}">
                  <el-input placeholder="请选择员工姓名" readonly v-model="emp.empName" @focus="changeEmp(emp, index)" disabled>
                    <i slot="suffix" class="el-input__icon el-icon-search" style="color:#0f00d1; font-weight: bolder"></i>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="是否帮工" :prop="'empList.' + index + '.helper'">
                  <template>
                    <el-radio v-model="emp.helper" :label=0 disabled>否</el-radio>
                    <el-radio v-model="emp.helper" :label=1 disabled>是</el-radio>
                  </template>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
          <el-card class="panel-group-top" style="margin-top: 10px;">
            <el-row v-for="(pro, index) in form.prodList" :key="pro.key" style="border: 1px solid #eeeeee;padding-top: 10px;margin-top: 5px">
              <el-col :span="6">
                <el-form-item label="产品名称" :prop="'prodList.' + index + '.productName'" :rules="{required: true, message: '产品名称不能为空', trigger: 'change'}">
                  <el-input placeholder="请选择产品名称" readonly v-model="pro.productName" @focus="changeProduct(pro, index)" disabled>
                    <i slot="suffix" class="el-input__icon el-icon-search" style="color:#0f00d1; font-weight: bolder"></i>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="产品价格" label-width="80px">
                  <div style="color: red; background: #eeeeee; padding: 0 2px; box-sizing: border-box;height: 35px;">
                    {{pro.minPrice !== null ? pro.minPrice+'元 - '+ pro.maxPrice+ '元' : null}}
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="产品规格" label-width="80px">
                  <el-input v-model="pro.productSpecification" placeholder="请输入产品规格" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="工序" label-width="55px">
                  <el-input v-model="pro.process" placeholder="请输入工序" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="加工数量" :prop="'prodList.' + index + '.productNum'" :rules="{required: true, validator: validator, trigger: 'change'}">
                  <el-input-number v-model="pro.productNum" :min="0" :max="10000" style="width: 100%;" @change="changeProductNum(index)" disabled></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="原材料" label-width="80px">
                  <el-input v-model="pro.productMaterial" placeholder="请输入原材料" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="单位" label-width="80px" :prop="'prodList.' + index + '.unit'">
                  <el-input v-model="pro.unit" placeholder="请输入单位" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="单价" label-width="55px" :prop="'prodList.' + index + '.price'" :rules="{ required: true, message: '单价不能为空', trigger: 'blur' }">
                  <el-input v-model="pro.price" placeholder="请输入单价" oninput ="value=value.replace(/[^0-9.]/g,'')" @input="inputProductNum(index)" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="总金额" :prop="'prodList.' + index + '.amount'" :rules="{ required:true, message: '总金额不能为空', trigger: 'blur' }">
                  <el-input v-model="pro.amount" placeholder="请输入加工总金额" oninput ="value=value.replace(/[^0-9.]/g,'')" disabled/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
          <el-card class="panel-group-top" style="margin-top: 10px;">
            <el-row v-for="(work, index) in form.worktimeList" :key="work.key">
              <el-col :span="6">
                <el-form-item
                  label="干活日期"
                  :prop="'worktimeList.' + index + '.date'"
                  :rules="{required: true, message: '干活日期不能为空', trigger: 'blur'}">
                  <el-date-picker disabled
                    v-model="work.date"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="选择干活日期" style="width: 100%">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item
                  label="开始时间"
                  :prop="'worktimeList.' + index + '.beginTime'"
                  :rules="{required: true, message: '开始时间不能为空', trigger: 'blur'}">
                  <el-time-picker disabled v-model="work.beginTime" placeholder="开始时间" value-format="HH:mm" format="HH:mm" style="width: 145px;"></el-time-picker>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item
                  label="结束时间"
                  :prop="'worktimeList.' + index + '.endTime'"
                  :rules="{required: true, message: '结束时间不能为空', trigger: 'blur'}">
                  <el-time-picker disabled v-model="work.endTime" value-format="HH:mm" format="HH:mm" placeholder="结束时间" style="width: 145px;"></el-time-picker>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item
                  label="有效时长"
                  :prop="'worktimeList.' + index + '.validHours'"
                  :rules="{required: true, message: '有效时长不能为空', trigger: 'blur'}">
                  <el-input v-model="work.validHours" placeholder="请输入有效工作时长" disabled/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
          <el-card class="panel-group-top" style="margin-top: 10px;">
            <el-row>
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input
                    type="textarea"
                    :rows="2"
                    placeholder="请输入备注"
                    v-model="form.remark" disabled>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="title !== '包活派工单详情'">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 包活工时查询 -->
    <el-dialog class="my-dialog" title="查询员工总工时" :visible.sync="opena" width="1200px" append-to-body :close-on-click-modal="false">
      <el-table :data="baohuogsList">
        <el-table-column label="年份" align="center" prop="year" />
        <el-table-column label="月份" align="center" prop="month" />
        <el-table-column label="员工姓名" align="center" prop="employeeName" />
        <el-table-column label="包活总工时" align="center" prop="workOrderHours" />
      </el-table>
    </el-dialog>

    <!-- 选择员工信息 -->
    <el-dialog title="双击选择员工" :visible.sync="emp.open" width="900px" append-to-body top="6vh">
      <div>
        <el-form :model="emp.queryParams" :inline="true" label-width="70px">
          <el-form-item label="员工名称" prop="name" style="margin-bottom: 10px">
            <el-input
              v-model="emp.queryParams.name"
              placeholder="请输入员工名称"
              clearablesize="small"
              @keyup.enter.native="empQuery"
            />
          </el-form-item>
          <el-form-item style="margin-bottom: 10px">
            <el-button type="primary" icon="el-icon-search" size="small" @click="empQuery">搜索</el-button>
          </el-form-item>
        </el-form>

        <el-table border v-loading="emp.loading" :data="emp.list" @row-dblclick="empRowChange">
          <el-table-column label="员工姓名" align="center" prop="name" :show-overflow-tooltip="true" min-width="120"/>
          <el-table-column label="所属部门" align="center" prop="deptName" :show-overflow-tooltip="true" min-width="120"/>
          <el-table-column label="状态" align="center" prop="deleted">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.pay_del_status" :value="scope.row.deleted"/>
            </template>
          </el-table-column>
          <el-table-column label="性别" align="center" prop="sex">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex"/>
            </template>
          </el-table-column>
          <el-table-column label="年龄" align="center" prop="age" />
          <el-table-column label="手机号" align="center" prop="phone" min-width="100"/>
          <el-table-column label="身份证号" align="center" prop="idcard" min-width="100" />
        </el-table>

        <pagination
          v-show="emp.total>0"
          :total="emp.total"
          :page.sync="emp.queryParams.pageNum"
          :limit.sync="emp.queryParams.pageSize"
          @pagination="empQuery"
        />
        <div slot="footer" class="dialog-footer">
          <el-button @click="empCancel">取 消</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 选择产品信息 -->
    <el-dialog title="双击选择产品" :visible.sync="product.open" width="900px" append-to-body top="6vh">
      <div>
        <el-form :model="product.queryParams" :inline="true" label-width="70px">
          <el-form-item label="员工名称" prop="name" style="margin-bottom: 10px">
            <el-input
              v-model="emp.queryParams.name"
              placeholder="请输入员工名称"
              clearablesize="small"
              @keyup.enter.native="empQuery"
            />
          </el-form-item>
          <el-form-item style="margin-bottom: 10px">
            <el-button type="primary" icon="el-icon-search" size="small" @click="empQuery">搜索</el-button>
          </el-form-item>
        </el-form>

        <el-table border v-loading="product.loading" :data="product.list" @row-dblclick="productRowChange">
          <el-table-column label="ID" align="center" prop="id" v-if="true"/>
          <el-table-column label="产品名称" align="center" prop="productName" />
          <el-table-column label="工序" align="center" prop="process" />
          <el-table-column label="规格型号" align="center" prop="model" />
          <el-table-column label="产品单位" align="center" prop="danwei" />
          <el-table-column label="毛料名称" align="center" prop="originName" />
          <el-table-column label="毛料规格" align="center" prop="originModel" />
          <el-table-column label="毛料尺寸" align="center" prop="originSize" />
          <el-table-column label="毛料单位" align="center" prop="originDanwei" />
        </el-table>

        <pagination
          v-show="product.total>0"
          :total="product.total"
          :page.sync="product.queryParams.pageNum"
          :limit.sync="product.queryParams.pageSize"
          @pagination="productQuery"
        />
        <div slot="footer" class="dialog-footer">
          <el-button @click="productCancel">取 消</el-button>
        </div>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listWorkOrderBaohuo, listWorkOrderBaohuoSum, getWorkOrderBaohuo, delWorkOrderBaohuo, addWorkOrderBaohuo, updateWorkOrderBaohuo } from "@/api/pay/workOrderBaohuo";
import { listTenant } from "@/api/pay/tenant";
import { listEmployeeInfo } from "@/api/pay/employeeInfo";
import { listProducts } from "@/api/pay/products";
import { deptTreeSelect } from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import Decimal from "decimal.js";

export default {
  name: "WorkOrderBaohuo",
  dicts: ['pay_workshop', 'sys_user_sex', 'pay_del_status'],
  components: { Treeselect },
  data() {
    return {
      // 公司信息
      gsInfo:{
        tenantName:'',
        active_id:this.$store.state.user.tenantId,
        list:[]
      },
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 包活派工单表格数据
      workOrderBaohuoList: [],
      // 部门树选项
      deptOptions: undefined,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tenantId: undefined,
        archiveId: undefined,
        productId: undefined,
        deptId: undefined,
        workshop: undefined,
        name: undefined,
        content: undefined,
        productNum: undefined,
        price: undefined,
        unit: undefined,
        amount: undefined,
        beginTime: undefined,
        endTime: undefined,
        qualityName: undefined,
        qualityRemark: undefined,
        instorageTime: undefined,
        instorageDate: null,
        instorageName: undefined,
        instorageNum: undefined,
        managerName: undefined,
        deleted: undefined,
        workDate: null,
        empId: null,
        exportDate: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "工单名称不能为空", trigger: "blur" }
        ],
        deptId: [
          { required: true, message: "部门不能为空", trigger: "change" }
        ],
        instorageTime: [
          { required: true, message: "入库时间不能为空", trigger: "blur" }
        ]
      },
      // 选择员工
      employeeList: [],
      opena: false,
      queform: {
        date: undefined,
        deptId: undefined,
        tenantId: undefined,
      },
      baohuogsList: [],
      // 员工选择框
      emps: [],
      // 产品选择框
      prods: [],
      /** 选择员工*/
      emp: {
        // 是否显示弹出层
        open: false,
        // 列表遮罩层
        loading: true,
        // 列表查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          name: undefined
        },
        // 表格数据
        list: [],
        // 总条数
        total: 0,
        index: 0
      },
      /** 选择产品*/
      product: {
        // 是否显示弹出层
        open: false,
        // 列表遮罩层
        loading: true,
        // 列表查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          name: undefined
        },
        // 表格数据
        list: [],
        // 总条数
        total: 0,
        index: 0
      },
    };
  },
  created() {
    if (!this.$store.state.user.tenantId) {
      this.getGsInfoList()
    }else {
      this.gsInfo.active_id = this.$store.state.user.tenantId
      this.getList();
      this.getDeptTree();
      this.getlistEmployee();
    }
  },
  methods: {
    // 获取左侧公司列表
    getGsInfoList(){
      listTenant({ name: this.gsInfo.tenantName }).then(response => {
        if(response.rows.length>0){
          this.gsInfo.list = response.rows;
          this.gsInfo.active_id = this.gsInfo.list[0].id
          this.getList();
          this.getDeptTree();
          this.getlistEmployee();
        }else{
          this.$alert(`没有查到相关公司，暂无数据！`, `提示`, {
            type: 'warning'
          });
        }
      });
    },
    // 选择公司
    changCompany(id){
      this.gsInfo.active_id = id
      this.getList();
      this.getDeptTree();
      this.getlistEmployee();
    },
    handleBaohuogs() {
      this.queform.deptId = this.queryParams.deptId;
      this.queform.tenantId = this.gsInfo.active_id;
      if (this.queform.date != null && this.queform.date != '') {
        listWorkOrderBaohuoSum(this.queform).then(response => {
          this.baohuogsList = response.data
          this.opena = true;
        })
      } else {
        this.$modal.msgError("请选择要查询的年月");
      }
    },
    /** 查询时员工 */
    getlistEmployee() {
      listEmployeeInfo({ pageSize: 1000000000 }).then(response => {
        this.employeeList = response.rows
      });
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect({tenantId: this.gsInfo.active_id}).then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 查询包活派工单列表 */
    getList() {
      this.loading = true;
      this.queryParams.tenantId = this.gsInfo.active_id;
      listWorkOrderBaohuo(this.queryParams).then(response => {
        this.workOrderBaohuoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        archiveId: null,
        name: null,
        deptId: null,
        deptName: null,
        workshop: null,
        content: null,
        qualityName: null,
        qualityRemark: null,
        instorageTime: null,
        instorageName: null,
        instorageNum: null,
        managerName: null,
        deleted: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        empId: null,
        empList: [{
          empId: null,
          deptId: null,
          empName: null,
          helper: 0
        }],
        prodList: [{
          productId: null,
          productName: null,
          productNum: null,
          price: null,
          minPrice: null,
          maxPrice: null,
          amount: null,
          unit: null,
          productSpecification: null,
          process: null,
          productMaterial: null,
        }],
        worktimeList: [{
          date: null,
          beginTime: null,
          stime: null,
          endTime: null,
          etime: null,
          validHours: 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.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加包活派工单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getWorkOrderBaohuo(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.form.worktimeList.forEach(item => {
          var sh = new Date(item.stime).getHours();
          sh = sh < 10 ?  sh : sh;
          var sminute = new Date(item.stime).getMinutes();
          sminute = sminute < 10 ? '0' + sminute : sminute;
          var xh = new Date(item.etime).getHours();
          xh = xh < 10 ?  xh : xh;
          var xminute = new Date(item.etime).getMinutes();
          xminute = xminute < 10 ? '0' + xminute : xminute;
          this.$set(item,"beginTime",sh+":"+sminute);
          this.$set(item,"endTime",xh+":"+xminute);
        })
        this.open = true;
        this.title = "修改包活派工单";
      });
    },
    /** 详情按钮操作 */
    handleDetails(row) {
      this.reset();
      const id = row.id || this.ids;
      getWorkOrderBaohuo(id).then(response => {
        this.form = response.data;
        this.form.worktimeList.forEach(item => {
          var sh = new Date(item.stime).getHours();
          sh = sh < 10 ?  sh : sh;
          var sminute = new Date(item.stime).getMinutes();
          sminute = sminute < 10 ? '0' + sminute : sminute;
          var xh = new Date(item.etime).getHours();
          xh = xh < 10 ?  xh : xh;
          var xminute = new Date(item.etime).getMinutes();
          xminute = xminute < 10 ? '0' + xminute : xminute;
          this.$set(item,"beginTime",sh+":"+sminute);
          this.$set(item,"endTime",xh+":"+xminute);
        })
        this.open = true;
        this.title = "包活派工单详情";
      });
    },
    validator(rule, value, callback) {
      if(value == 0){
        return callback(new Error("加工数量不能为0"));
      }
      return callback();
    },
    /** 删除产品 */
    removePro(pro) {
      var index = this.form.prodList.indexOf(pro)
      if (index !== -1) {
        this.form.prodList.splice(index, 1)
      }
    },
    /** 新增产品 */
    addPro() {
      this.form.prodList.push({
        productId: null,
        productName: null,
        productNum: null,
        price: null,
        minPrice: null,
        maxPrice: null,
        amount: null,
        unit: null,
        productSpecification: null,
        process: null,
        productMaterial: null
      })
    },
    /** 删除时间段 */
    removeWork(item) {
      var index = this.form.worktimeList.indexOf(item)
      if (index !== -1) {
        this.form.worktimeList.splice(index, 1)
      }
    },
    /** 新增时间段 */
    addWork() {
      this.form.worktimeList.push({
        date: null,
        stime: null,
        etime: null,
        validHours: null
      })
    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.form,555555);
      this.form.worktimeList.forEach(item => {
        item.stime = item.date + ' ' + item.beginTime + ':00';
        item.etime = item.date + ' ' + item.endTime + ':00';
      })
      var isHour = true
      if(this.form.worktimeList.length > 0){
        for(var i=0; i<this.form.worktimeList.length; i++){
          if(new Date(this.form.worktimeList[i].etime).getTime() <= new Date(this.form.worktimeList[i].stime).getTime()){
            isHour = false
            this.$alert('结束时间应大于开始时间', '信息', {
              confirmButtonText: '确定',
              customClass:'message_box_alert'
            }).catch((err) => {
              console.log(err)
            })
            break;
          }
        }
      }
      if(this.form.empList.length > 1){
        for(var i=0; i<this.form.empList.length; i++){
          for(var j=i+1; j<this.form.empList.length; j++){
            if(this.form.empList[i].empName == this.form.empList[j].empName && this.form.empList[i].empId == this.form.empList[j].empId){
              isHour = false;
              this.$alert('员工不能重复', '信息', {
                confirmButtonText: '确定',
                customClass: 'message_box_alert'
              }).catch((err) => {
                console.log(err)
              })
              break;
            }
          }
        }
      }
      if(isHour){
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.buttonLoading = true;
            this.form.tenantId = this.gsInfo.active_id;
            if (this.form.id != null) {
              updateWorkOrderBaohuo(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            } else {
              addWorkOrderBaohuo(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            }
          }
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除包活派工单编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delWorkOrderBaohuo(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      if(this.queform.date == null) {
        this.$message({
          message: '请选择导出月份',
          type: 'warning'
        });
      } else {
        this.queryParams.exportDate = this.queform.date
        this.download('pay/workOrderBaohuo/export', {
          ...this.queryParams
        }, `包活信息_${new Date().getTime()}.xlsx`)
      }
    },
    // 新增员工
    addEmp() {
      this.form.empList.push({
        empId: null,
        deptId: null,
        empName: null,
        helper: 0
      })
    },
    removeEmp(emp) {
      var index = this.form.empList.indexOf(emp)
      if (index !== -1) {
        this.form.empList.splice(index, 1)
      }
    },
    changeProductNum(index) {
      if(this.form.prodList[index].price != null && this.form.prodList[index].price != '') {
        this.form.prodList[index].amount = JSON.parse(new Decimal(this.form.prodList[index].productNum).mul(new Decimal(this.form.prodList[index].price)));
      }else{
        this.form.prodList[index].amount = null
      }
    },
    inputProductNum(index) {
      if(this.form.prodList[index].price != null && this.form.prodList[index].price != '') {
        this.form.prodList[index].amount = JSON.parse(new Decimal(this.form.prodList[index].productNum).mul(new Decimal(this.form.prodList[index].price)));
      }else{
        this.form.prodList[index].amount = null
      }
    },
    // 添加包活派工单 选择员工
    changeEmp(val,index){
      console.log(val,index,222);
      this.emp.open = true;
      this.emp.index = index;
      this.emp.queryParams.pageNum = 1;
      this.empQuery();
    },
    /** 员工列表查询 */
    empQuery() {
      this.emp.loading = true;
      this.emp.queryParams.tenantId = this.gsInfo.active_id
      listEmployeeInfo(this.emp.queryParams).then(response => {
        this.emp.list = response.rows;
        this.emp.total = response.total;
        this.emp.loading = false;
      });
    },
    /** 员工选择弹出框关闭*/
    empCancel() {
      this.emp.open = false
    },
    // 员工选择 选中数据
    empRowChange(val) {
      this.form.empList[this.emp.index].empName = val.name;
      this.form.empList[this.emp.index].empId = val.id;
      this.form.empList[this.emp.index].deptId = val.deptId
      console.log(this.form.empList);
      this.emp.open = false;
    },
    // 添加包活派工单 选择产品
    changeProduct(val,index){
      console.log(val,index,333);
      this.product.open = true;
      this.product.index = index;
      this.product.queryParams.pageNum = 1;
      this.productQuery();
    },
    /** 产品列表查询 */
    productQuery() {
      this.product.loading = true;
      this.product.queryParams.tenantId = this.gsInfo.active_id
      listProducts(this.emp.queryParams).then(response => {
        this.product.list = response.rows;
        this.product.total = response.total;
        this.product.loading = false;
      });
    },
    /** 产品选择弹出框关闭*/
    productCancel() {
      this.product.open = false
    },
    // 产品选择 选中数据
    productRowChange(val) {
      this.form.prodList[this.product.index].productName = val.productName;
      this.form.prodList[this.product.index].productId = val.id;
      this.form.prodList[this.product.index].minPrice = val.minPrice;
      this.form.prodList[this.product.index].maxPrice = val.maxPrice;
      this.form.prodList[this.product.index].productSpecification = val.model;
      this.form.prodList[this.product.index].process = val.process;
      this.form.prodList[this.product.index].productMaterial = val.materialName;
      this.form.prodList[this.product.index].process = val.process;
      console.log(this.form.prodList);
      this.product.open = false;
    },
  }
};
</script>

<style scoped lang="scss">
.app-container {
  display: flex;
  .company {
    border-radius: 5px;
    width: 230px;
    height: calc(100vh - 115px);
    overflow-y: auto;
    .cp-content {
      margin-top: 20px;
      .cp-item {
        cursor: pointer;
        padding: 6px 10px 6px 5px;
        color: #424242;
        font-size: 14px;
        &:hover {
          background: #f6f6f6;
        }
      }
      .active{
        background: #edf6ff;
      }
    }
  }
  .content{
    padding-left: 15px;
    width: calc(100% - 250px);
    .el-button--medium {
      padding: 2px 0px;
    }
  }
  .content-all{
    width: 100%;
    .el-button--medium {
      padding: 2px 0px;
    }
  }
}

.my-dialog1 {
  ::v-deep .el-form-item{
    margin-bottom: 15px!important;
  }

  .el-dialog__header {
    border-bottom: 1px solid #e5e7eb;
  }
  .el-dialog__title {
    font-size: 15px;
  }
  .el-dialog__body {
    border-bottom: 1px solid #e5e7eb;
  }
}
</style>
