<template>
  <div class="plan_container">
    <el-form
      :model="addForm"
      ref="addFormRef"
      :rules="rules"
      label-width="100px"
    >
      <el-row>
        <!-- <el-col :span="6">
          <el-form-item label="计划单号：" prop="planCode">
            <el-input
              v-model="addForm.planCode"
              size="small"
              placeholder="自动带出"
              disabled
            ></el-input>
          </el-form-item>
        </el-col> -->
        <el-col :span="6">
          <el-form-item label="计划名称：" prop="planName">
            <el-input
              v-model.trim="addForm.planName"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="审批部门：" prop="verifyDeptCode">
            <deptSelect
              v-model="addForm.verifyDeptCode"
              @change="searchDeptNodeClick"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="审批人：" prop="approvalUserId">
            <personSelect
              ref="executorRef"
              v-model="addForm.approvalUserId"
              :init="false"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="紧急程度：" prop="urgent">
            <DictSelection
              dictName="紧急程度"
              clearable
              v-model="addForm.urgent"
            >
            </DictSelection>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <div class="btns_wrapper">
            <el-button type="primary" size="small" @click="selectRepairNotes"
              >选择报修记录</el-button
            >
            <el-button
              type="primary"
              size="small"
              @click="handleBatchRemoveEqui"
              >删除</el-button
            >
          </div>
        </el-col>
      </el-row>
    </el-form>
    <p>设备明细</p>
    <el-table
      :data="equipmentData"
      border
      style="margin-top: 10px"
      @selection-change="equiMultipleSelectChange"
    >
      <el-table-column type="selection" align="center" />
      <el-table-column label="报修记录编码" prop="code" />
      <el-table-column label="设备编码" prop="deviceCode" />
      <el-table-column label="设备名称" prop="deviceName" />
      <el-table-column label="计划完成时间" prop="expectedTime" width="220">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.expectedTime"
            size="small"
            disabled
            placeholder="设置执行人自动带出"
            style="width: 100%"
          />
        </template>
      </el-table-column>
      <!--      <el-table-column label="执行部门" prop="deptName">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.deptName"
            size="small"
            disabled
            placeholder="设置执行人自动带出"
          />
        </template>
      </el-table-column> -->
      <el-table-column label="执行人" prop="workOrderExecutorId">
        <template slot-scope="scope">
          <personSelect
            v-if="scope.$index == 0"
            :disabled="true"
            v-model="scope.row.workOrderExecutorId"
            placeholder="设置"
            @click.native="settingExecutor(scope.$index, scope.row)"
          />
          <personSelect
            v-else
            readonly
            v-model="scope.row.workOrderExecutorId"
            placeholder="同上"
            @click.native="dittoName(scope.$index, scope.row)"
            :disabled="true"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="handleRemoveEquiItem(scope.$index)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="btns">
      <el-button type="primary" size="small" @click="handleSubmitAdd"
        >提交</el-button
      >
      <el-button size="small" @click="$router.go(-1)">返回</el-button>
    </div>

    <!-- 选择报修记录弹窗 -->
    <ele-modal
      title="选择报修记录"
      :visible.sync="selectNotesVisible"
      :before-close="closeRepairNotesDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="65%"
    >
      <div class="search_msg">
        <el-input
          v-model="code"
          style="width: 30%; margin-right: 20px"
          clearable
          placeholder="请输入编码"
        ></el-input>
        <el-button type="primary" @click="searchByKeyWords">确定</el-button>
        <el-button type="primary" @click="resetSearch">重置</el-button>
      </div>
      <el-table
        :data="notesData"
        @selection-change="notesMultipleSelectChange"
        ref="multipleTable"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          label="报修记录编码"
          prop="code"
          align="center"
        ></el-table-column>
        <el-table-column
          label="设备编码"
          prop="deviceCode"
          align="center"
        ></el-table-column>
        <el-table-column
          label="设备名称"
          prop="deviceName"
          align="center"
        ></el-table-column>
        <el-table-column label="来源" align="center">
          <template slot-scope="{ row }">
            <span>{{ getDictValue('报修来源', row.sourceType) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="报修人"
          prop="requestUserName"
          width="70"
          align="center"
        ></el-table-column>
        <el-table-column
          label="报修时间"
          prop="createTime"
          width="150"
          align="center"
        ></el-table-column>
        <el-table-column
          label="期望完成时间"
          prop="expectedTime"
          width="150"
          align="center"
        ></el-table-column>
      </el-table>
      <div class="pagination_wrapper">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 15, 20, 30, 50]"
          :current-page.sync="pagination.pageNum"
          :page-size.sync="pagination.size"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        >
        </el-pagination>
      </div>
      <template v-slot:footer>
        <el-button type="primary" size="small" @click="handleConfirm"
          >确定</el-button
        >
        <el-button size="small" @click="closeRepairNotesDialog">关闭</el-button>
      </template>
    </ele-modal>

    <!-- 设置执行人弹窗 -->
    <ele-modal
      title="派单"
      :visible.sync="settingExecutorVisible"
      class="setting_executor_dialog"
      :before-close="closeSettingExecutorDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="60%"
    >
      <div>
        <el-form
          :model="infoData"
          :rules="infoFormRules"
          ref="infoFormRef"
          label-width="130px"
        >
          <el-row>
            <el-col :span="8">
              <el-form-item label="报修记录编号：">
                <span>{{ infoData.code }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="设备编码：">
                <span>{{ infoData.deviceCode }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="设备名称：">
                <span>{{ infoData.deviceName }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="设备型号：">
                <span>{{
                  infoData.category && infoData.category.modelType
                }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="设备位置：">
                <span>
                  {{ infoData.position }}
                </span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="故障描述：">
                <span>{{ infoData.remark }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <!--          <el-row>
            <el-col :span="16">
              <el-form-item label="图片：">
                <el-image
                  v-for="(item, index) in infoData.repairsImg"
                  :key="index"
                  style="width: 100px; height: 100px; margin-right: 5px"
                  :src="item.url"
                  :preview-src-list="[item.url]"
                >
                </el-image>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="视频：">
                <span>{{ infoData.repairsVideo }}</span>
              </el-form-item>
            </el-col>
          </el-row> -->
          <el-row class="valid_row">
            <el-col :span="8">
              <el-form-item label="计划完成时间：">
                <el-date-picker
                  v-model="infoData.expectedTime"
                  type="datetime"
                  size="small"
                  placeholder="选择日期时间"
                  value-format="yyyy-MM-dd HH:mm:ss"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="执行部门：" prop="deptCode">
                <deptSelect
                  v-model="infoData.deptCode"
                  @change="deptNodeClick"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="执行人：" prop="workOrderExecutorId">
                <personSelect
                  ref="setExecutor"
                  v-model="infoData.workOrderExecutorId"
                  :init="false"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="维修方案：">
                <el-input
                  type="textarea"
                  :rows="3"
                  v-model="infoData.maintenanceContent"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template v-slot:footer>
        <el-button type="primary" size="small" @click="saveSetting"
          >保存</el-button
        >
        <el-button size="small" @click="closeSettingExecutorDialog"
          >关闭</el-button
        >
      </template>
    </ele-modal>
  </div>
</template>

<script>
  import personSelect from '@/components/CommomSelect/person-select.vue';
  import deptSelect from '@/components/CommomSelect/dept-select.vue';
  import { getPage, savePlanRepair } from '@/api/maintenance/repair_report';
  import { getAssetInfo } from '@/api/ledgerAssets';
  import dictMixins from '@/mixins/dictMixins';
  export default {
    mixins: [dictMixins],
    components: {
      personSelect,
      deptSelect
    },
    data() {
      return {
        equipmentData: [], // 设备明细表格
        equiSelection: [], // 设备明细 - 表格多选
        selectNotesVisible: false, // 弹窗
        notesData: [], // 弹窗- 报修记录表格
        notesSelection: [], // 弹窗 - 表格多选
        code: '', // 弹窗 - 关键字搜索
        addForm: {},
        pagination: {
          pageNum: 1,
          size: 10
        },
        total: 0,
        rules: {
          planName: [
            { required: true, message: '请输入计划名称', trigger: 'blur' }
          ],
          urgent: [
            { required: true, message: '请选择紧急程度', trigger: 'change' }
          ],
          verifyDeptCode: [
            { required: true, message: '请选择审批部门', trigger: 'change' }
          ],
          approvalUserId: [
            { required: true, message: '请选择审批人', trigger: 'change' }
          ]
        },
        settingIndex: null, // 保存的设备明细表格行index
        settingExecutorVisible: false, // 设置执行人弹窗
        infoData: { deptCode: '' }, // 设置执行人弹窗详情数据
        infoFormRules: {
          deptCode: [
            { required: true, message: '请选择执行部门', trigger: 'change' }
          ],
          workOrderExecutorId: [
            { required: true, message: '请选择执行人', trigger: 'change' }
          ]
        }
      };
    },
    created() {
      this.requestDict('报修来源');
    },
    methods: {
      //选择部门(搜索)
      searchDeptNodeClick(info) {
        // 根据部门获取人员
        const params = { groupId: info };
        this.$nextTick(() => {
          this.$refs.executorRef.getList(params);
        });
      },

      // // 获取详情
      // async _getPlanInfo () {
      //   const res = await maintenancePlan.planInfoDetailApi(this.$route.query.id)
      //   this.addForm = res.data
      //   this.equipmentData = res.data.planDetailRespList
      // },

      // 设备明细 - 表格多选
      equiMultipleSelectChange(val) {
        this.equiSelection = val;
      },
      // 设备明细 - 删除表格行
      handleRemoveEquiItem(index) {
        this.equipmentData.splice(index, 1);
      },
      // 设备明细 - 批量删除行
      handleBatchRemoveEqui() {
        this.equiSelection.forEach((item) => {
          const index = this.equipmentData.findIndex((c) => c.id === item.id);
          this.equipmentData.splice(index, 1);
        });
      },

      // 获取报修详情
      getSbinfo(params) {
        getAssetInfo(params).then((res) => {
          console.log(res, 'res');
          if (res) {
            this.infoData = res;
            this.$set(
              this.infoData,
              'position',
              res.positionList[0].pathName ? res.positionList[0].pathName : ''
            );
            this.$set(this.infoData, 'deviceCode', res.code);
            this.$set(this.infoData, 'deviceName', res.name);
          }
        });
      },

      // 设备明细 - 打开设置执行人弹窗
      async settingExecutor(index, row) {
        console.log('打开设置执行人弹窗', index, row);
        this.getSbinfo(row.deviceId);
        this.settingIndex = index;
        this.settingExecutorVisible = true;
        this.$set(this.infoData, 'remark', row.remark);
        this.$set(this.infoData, 'code', row.code);
      },

      // 点击同上
      async dittoName(index, row) {
        if (!this.equipmentData[0].workOrderExecutorId) {
          this.$message.warning('请先设置第一条数据的执行人');
        } else {
          this.settingExecutor(index, row);
        }
      },

      // 选择部门(搜索)
      deptNodeClick(info) {
        const params = { groupId: info };
        this.$nextTick(() => {
          this.$refs.setExecutor.getList(params);
        });
      },

      // 弹窗 - 关闭
      closeRepairNotesDialog() {
        this.selectNotesVisible = false;
        this.notesSelection = [];
        this.$refs.multipleTable.clearSelection();
      },
      // 弹窗 - 确认选择报修记录
      handleConfirm() {
        let arr = [];
        this.notesSelection.map((item) => {
          if (item) {
            arr.push(item);
          }
        });
        this.notesSelection = arr;
        this.equipmentData = this.notesSelection;
        this.equipmentData.forEach((item) => {
          item['repairInfoId'] = item.id;
          item['plannedTime'] = item.expectedTime;
        });
        this.closeRepairNotesDialog();
      },
      // 弹窗 - 打开选择报修记录
      selectRepairNotes() {
        this.selectNotesVisible = true;
        this.$nextTick(async () => {
          await this._getNotesData();
          // 将设备明细回显到 报修记录表格并勾选已有的
          if (this.equipmentData.length > 0) {
            console.log(this.equipmentData);
            console.log(this.notesData);
            this.equipmentData.forEach((item) => {
              const row = this.notesData.find(
                (c) => c.id === item.repairInfoId
              );
              this.$refs.multipleTable.toggleRowSelection(row, true);
            });
          }
        });
      },

      // 弹窗 - 报修记录表格数据
      async _getNotesData() {
        let params = {
          ...this.pagination,
          code: this.code,
          statusList: '0,6'
        };
        const res = await getPage(params);
        this.notesData = res.list;
        this.total = res.count;
      },

      // 弹窗 - 分页器方法
      handleCurrentChange(page) {
        this.pagination.pageNum = page;
        this._getNotesData();
      },
      handleSizeChange(size) {
        this.pagination.pageNum = 1;
        this.pagination.size = size;
        this._getNotesData();
      },

      // 弹窗 - 按关键字搜索
      searchByKeyWords() {
        this._getNotesData();
      },
      resetSearch() {
        this.code = '';
        this._getNotesData();
      },

      // 弹窗 - 表格多选
      notesMultipleSelectChange(val) {
        this.notesSelection = val;
      },

      // 弹窗 - 关闭设置执行人弹窗
      closeSettingExecutorDialog() {
        this.infoData = { deptCode: '' };
        this.$refs.infoFormRef.resetFields();
        this.settingExecutorVisible = false;
      },

      // 弹窗 - 保存设置执行人
      saveSetting() {
        this.$refs.infoFormRef.validate((valid) => {
          if (valid) {
            this.$set(
              this.equipmentData[this.settingIndex],
              'expectedTime',
              this.infoData.expectedTime
            );
            this.$set(
              this.equipmentData[this.settingIndex],
              'deptCode',
              this.infoData.deptCode
            );
            this.$set(
              this.equipmentData[this.settingIndex],
              'workOrderExecutorId',
              this.infoData.workOrderExecutorId
            );
            this.$set(
              this.equipmentData[this.settingIndex],
              'maintenanceContent',
              this.infoData.maintenanceContent
            );
            console.log('[this.settingIndex]', [this.settingIndex]);
            if (!this.settingIndex) {
              this.equipmentData.map((item) => {
                // item.workOrderExecutorName = this.infoData.workOrderExecutorName
                item.workOrderExecutorId = this.infoData.workOrderExecutorId;
                // item.workOrderExecutorPhone = this.infoData.workOrderExecutorPhone
                // item.deptName = this.infoData.deptName
                item.maintenanceContent = this.infoData.maintenanceContent;
              });
            }

            console.log(' this.equipmentData', this.equipmentData);
            this.closeSettingExecutorDialog();
          }
        });
      },
      // 提交新增
      handleSubmitAdd() {
        this.$refs.addFormRef.validate(async (valid) => {
          if (valid) {
            if (this.equipmentData.length === 0) {
              return this.$message.warning('请选择设备报修记录！');
            }
            let data = JSON.parse(JSON.stringify(this.addForm));
            data['planEquiList'] = this.equipmentData;
            // let api = maintenancePlan.savePlanInfo
            let msg = '新增成功！';
            // 修改
            if (this.$route.query.id) {
              delete data.planDetailRespList;
              // api = maintenancePlan.updatePlanInfo
              msg = '修改成功！';
            }
            // console.log(data)
            const res = await savePlanRepair(data);
            // console.log('保存新增：', res)
            this.$message.success(msg);
            this.$router.go(-1);
          }
        });
      }
    }
  };
</script>

<style lang="scss" scoped>
  .plan_container {
    background-color: #fff;
    padding: 20px 30px;
    margin-top: 10px;
  }
  .btns_wrapper {
    text-align: right;
    margin: 15px 0;
  }
  .btns {
    text-align: center;
    margin-top: 15px;
  }
  ::v-deep .el-table th.el-table__cell {
    background-color: #f0f3f3;
  }

  .search_msg {
    margin-bottom: 5px;
  }
  .pagination_wrapper {
    text-align: right;
    padding-top: 10px;
  }
  .dialog_btns {
    text-align: center;
    padding: 10px 0;
  }

  .setting_executor_dialog {
    .setting_btns {
      text-align: right;
    }
    .repair_row {
      margin-bottom: 15px;
    }
    ::v-deep .valid_row {
      .el-form-item {
        margin-bottom: 20px;
      }
      .el-form-item__error {
        padding-top: 0;
      }
      .el-date-editor.el-input {
        width: 190px;
      }
    }
  }
</style>
