<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属项目" prop="projectId" v-if="showPro">
        <el-select
          v-model="queryParams.projectId"
          placeholder="请选择所属项目"
          filterable
          clearable
        >
          <el-option
            v-for="(item, index) in projectOptions"
            :key="index"
            :label="item.projectName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="责任主体" prop="projectDeptId" v-hasPermi="['project:project:zgs']">
        <el-select v-model="queryParams.deptId" placeholder="请选择责任主体" clearable>
          <el-option
            v-for="dict in projectDeptOptions"
            :key="dict.deptId"
            :label="dict.deptName"
            :value="dict.deptId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="问题分类" prop="projectDeptId" v-hasPermi="['project:project:zgs']">
        <el-select v-model="queryParams.roleTypes" placeholder="请选择问题分类" clearable>
          <el-option
            v-for="dict in roleTypeOpts"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="整改人" prop="lordSent">
        <el-input
          v-model="queryParams.lordSent"
          placeholder="请输入整改人姓名/联系方式"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </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-button type="success" icon="el-icon-finished" size="mini" @click="batchSubmitForm" :disabled="multiple" >批量提交</el-button>
      </el-form-item>
    </el-form>

    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-table v-loading="loading" :data="smzSspProblemmodifyDraftList" :row-class-name="rowIndex" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center"/>
        <el-table-column label="序号" align="center" prop="index" width="50"/>
        <el-table-column label="问题图片" align="center" prop="smarkUrl" width="240">
          <template slot-scope="scope">
            <image-upload v-model="scope.row.smarkUrl" :limit="9" :isShowTip="false" />
          </template>
        </el-table-column>
        <el-table-column label="所属项目" align="center" prop="problemArea" width="150"/>
        <el-table-column label="隐患类型" align="center" prop="dangerType" width="170">
          <template slot-scope="scope">
            <el-select
              v-if="scope.row.infoType==1"
              v-model="scope.row.dangerType"
              placeholder="请选择隐患类型"
            >
              <el-option
                v-for="dict in dict.type.ssp_zlyhlx"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
            <el-select
              v-if="scope.row.infoType==0"
              v-model="scope.row.dangerType"
              placeholder="请选择隐患类型"
            >
              <el-option
                v-for="dict in dict.type.ssp_aqyhlx"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="施工部位" align="center" prop="workParts" width="180">
          <template slot-scope="scope">
            <el-input v-model="scope.row.workParts" placeholder="请输入施工部位" type="textarea" :rows="3"/>
          </template>
        </el-table-column>
        <el-table-column label="整改要求" align="center" prop="changeInfo" width="180">
          <template slot-scope="scope">
            <el-input v-model="scope.row.changeInfo" placeholder="请输入整改要求" type="textarea" :rows="3"/>
          </template>
        </el-table-column>
        <el-table-column label="问题人员" align="center" prop="lordSentUser" width="260">
          <template slot-scope="scope">
            <el-row style="line-height: 36px;margin-bottom: 5px;">
              <el-col :span="6">整改人：</el-col>
              <el-col :span="18">
                <el-select
                  v-model="scope.row.lordSentUser"
                  placeholder="请选择整改人"
                  style="width: 100%"
                  @change="selectLordSentUser($event,scope.row)"
                >
                  <el-option-group
                    v-for="group in findProjectAllUnitUser(scope.row.projectId)"
                    :key="group.unitId + ''"
                    :label="group.unitName + ' [' + group.unitTypeName + '] '"
                  >
                    <el-option
                      v-for="item in group.userinfoList"
                      :key="item.phonenumber"
                      :label="item.nickName + ' [' + item.jobTypeName + '] '"
                      :value="item.phonenumber"
                    >
                    </el-option>
                  </el-option-group>
                </el-select>
              </el-col>
            </el-row>
            <el-row style="line-height: 36px;margin-bottom: 5px;">
              <el-col :span="6">抄送人：</el-col>
              <el-col :span="18">
                <el-select
                  v-model="scope.row.copySendUser"
                  placeholder="请选择整改人"
                  style="width: 100%"
                  @change="selectCopySendUser($event,scope.row)"
                >
                  <el-option-group
                    v-for="group in findProjectAllUnitUser(scope.row.projectId)"
                    :key="group.unitId + ''"
                    :label="group.unitName + ' [' + group.unitTypeName + '] '"
                  >
                    <el-option
                      v-for="item in group.userinfoList"
                      :key="item.phonenumber"
                      :label="item.nickName + ' [' + item.jobTypeName + '] '"
                      :value="item.phonenumber"
                    >
                    </el-option>
                  </el-option-group>
                </el-select>
              </el-col>
            </el-row>
            <el-row style="line-height: 36px;margin-bottom: 5px;">
              <el-col :span="6">复检人：</el-col>
              <el-col :span="18">
                <el-select
                  v-model="scope.row.recheckSendUser"
                  placeholder="请选择整改人"
                  style="width: 100%"
                  @change="selectRecheckSendUser($event,scope.row)"
                >
                  <el-option-group
                    v-for="group in findProjectAllUnitUser(scope.row.projectId)"
                    :key="group.unitId + ''"
                    :label="group.unitName + ' [' + group.unitTypeName + '] '"
                  >
                    <el-option
                      v-for="item in group.userinfoList"
                      :key="item.phonenumber"
                      :label="item.nickName + ' [' + item.jobTypeName + '] '"
                      :value="item.phonenumber"
                    >
                    </el-option>
                  </el-option-group>
                </el-select>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="整改截至时间" align="center" prop="nickedTime" width="180">
          <template slot-scope="scope">
            <el-date-picker
              v-model="scope.row.nickedTime"
              type="date"
              value-format="yyyy-MM-dd HH:ss"
              placeholder="选择截至时间" style="width:160px;">
            </el-date-picker>
          </template>
        </el-table-column>
        <el-table-column label="草稿信息" align="left" prop="createUser" width="180">
          <template slot-scope="scope">
            <div><i class="el-icon-user"></i>{{scope.row.createUserName}}</div>
            <div><i class="el-icon-phone-outline"></i>{{scope.row.createUser}}</div>
            <div><el-tag type="info">{{scope.row.createUserDeptName}}</el-tag></div>
            <div><i class="el-icon-alarm-clock"></i>{{ parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}") }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="70">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit-outline"
              @click="submitForm(scope.row)"
              v-hasPermi="['trouble:smzSspProblemmodifyDraft:edit']"
            >提交</el-button>
            <el-button
              class="bt2"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['trouble:smzSspProblemmodifyDraft:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { listSmzSspProblemmodifyDraft, updateSmzSspProblemmodifyDraft, batchUpdateSmzSspProblemmodifyDraft, delSmzSspProblemmodifyDraft } from "@/api/trouble/smzSspProblemmodifyDraft";

export default {
  name: "SmzSspProblemmodifyDraft",
  dicts: ["ssp_zlyhlx", "ssp_aqyhlx"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中数组下标
      indexs: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 随手拍问题整改质量留痕信息表格数据
      smzSspProblemmodifyDraftList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        projectId: null,
        infoType: "0",
        lordSent: null,
        roleType: null,
        projectDeptId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      roleTypeOpts:[
        {label:'集团',value:3},
        {label:'子公司',value:4},
        {label:'甲方代表',value:5},
        {label:'监理单位',value:6},
        {label:'总包单位',value:7}
      ],
      showPro:false,
      projectOptions: [],
      projectDeptOptions:[],
      projectIds:[],
      projectUnitUsers:[],
    };
  },
  created() {
    this.getList();
    this.initMyProject();
    this.$api.publics.getZgsDeptList().then((d) => {
      this.projectDeptOptions = d?.data || [];
    });
  },
  methods: {
    // 查询和我相关的项目信息
    initMyProject() {
      // 获取项目列表的接口
      this.$api.publics.getMyProjectList({}).then((response) => {
        this.projectOptions = response.rows;
        if (response.rows.length > 1) {
          this.showPro = true;
        }
      });
    },
    /** 查询随手拍问题整改质量留痕信息列表 */
    getList() {
      this.loading = true;
      listSmzSspProblemmodifyDraft(this.queryParams).then(response => {
        response.rows.forEach(row => {
          if(!this.projectIds.includes(row.projectId)){
            this.projectIds.push(row.projectId);
          }
        });
        this.projectIds.forEach(proj => {
          this.$api.publics.selectProjectAllUnitUser({projectId: proj})
          .then((d) => {
            this.projectUnitUsers.push({projectId:proj,data:d.data});
          });
        })
        this.smzSspProblemmodifyDraftList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    findProjectAllUnitUser(projectId){
      for(let i=0;i<this.projectUnitUsers.length;i++){
        if(this.projectUnitUsers[i].projectId==projectId){
          return this.projectUnitUsers[i].data;
        }
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.indexs = selection.map(item => item.index)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 提交按钮 */
    submitForm(row) {
      if(!row.smarkUrl){
        this.$message.error("请上传隐患图片！");
        return false;
      }
      if(!row.dangerType){
        this.$message.error("请选择隐患类型！");
        return false;
      }
      if(!row.workParts){
        this.$message.error("请输入施工部位！");
        return false;
      }
      if(!row.changeInfo){
        this.$message.error("请输入整改要求！");
        return false;
      }
      if(!row.lordSent || !row.lordSentUser){
        this.$message.error("请选择整改人！");
        return false;
      }
      if(!row.copySend || !row.copySendUser){
        this.$message.error("请选择抄送人！");
        return false;
      }
      if(!row.recheckSend || !row.recheckSendUser){
        this.$message.error("请选择复检人！");
        return false;
      }
      if(!row.nickedTime){
        row.nickedTime = row.nickedTime+" 23:59"
        this.$message.error("请选择整改截至时间！");
        return false;
      }
      if(row.lordSent==row.copySend){
        this.$message.error("整改人和抄送人不能是同一人！");
        return false;
      }
      if(row.lordSent==row.recheckSend){
        this.$message.error("整改人和复检人不能是同一人！");
        return false;
      }
      this.loading = true;
      updateSmzSspProblemmodifyDraft(row).then(response => {
        this.$modal.msgSuccess("提交成功！");
        this.loading = false;
        this.getList();
      });
    },
    /** 批量提交按钮 */
    batchSubmitForm() {
      let indexs = this.indexs;
      let rows = [];
      for(let i=0;i<indexs.length;i++){
        let row = this.smzSspProblemmodifyDraftList[(indexs[i]-1)];
        if(!row.smarkUrl){
          this.$message.error("请上传隐患图片！");
          return false;
        }
        if(!row.dangerType){
          this.$message.error("请选择隐患类型！");
          return false;
        }
        if(!row.workParts){
          this.$message.error("请输入施工部位！");
          return false;
        }
        if(!row.changeInfo){
          this.$message.error("请输入整改要求！");
          return false;
        }
        if(!row.lordSent || !row.lordSentUser){
          this.$message.error("请选择整改人！");
          return false;
        }
        if(!row.copySend || !row.copySendUser){
          this.$message.error("请选择抄送人！");
          return false;
        }
        if(!row.recheckSend || !row.recheckSendUser){
          this.$message.error("请选择复检人！");
          return false;
        }
        if(!row.nickedTime || !row.nickedTime){
          this.$message.error("请选择整改截至时间！");
          return false;
        }
        if(row.lordSent==row.copySend){
          this.$message.error("整改人和抄送人不能是同一人！");
          return false;
        }
        if(row.lordSent==row.recheckSend){
          this.$message.error("整改人和复检人不能是同一人！");
          return false;
        }
        rows.push(row);
      }
      this.loading = true;
      batchUpdateSmzSspProblemmodifyDraft(rows).then(response => {
        this.$modal.msgSuccess("提交成功！");
        this.loading = false;
        this.getList();
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const indexs = row.index || this.index;
      this.$modal.confirm('是否确认删除隐患问题编号为"' + indexs + '"的数据项？').then(function() {
        return delSmzSspProblemmodifyDraft(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 行内序号 */
    rowIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    selectLordSentUser(val,row){
      let data=[];
      for(let i=0;i<this.projectUnitUsers.length;i++){
        if(this.projectUnitUsers[i].projectId==row.projectId){
          data = this.projectUnitUsers[i].data;
        }
      }
      data.forEach((item) => {
        item.userinfoList.forEach((u) => {
          if (u.phonenumber == val) {
            row.lordSent = u.nickName + " [" + u.jobTypeName + "] ";
          }
        });
      });
    },
    selectCopySendUser(val,row){
      let data=[];
      for(let i=0;i<this.projectUnitUsers.length;i++){
        if(this.projectUnitUsers[i].projectId==row.projectId){
          data = this.projectUnitUsers[i].data;
        }
      }
      data.forEach((item) => {
        item.userinfoList.forEach((u) => {
          if (u.phonenumber == val) {
            row.copySendUser
            row.copySend = u.nickName + " [" + u.jobTypeName + "] ";
          }
        });
      });
    },
    selectRecheckSendUser(val,row){
      let data=[];
      for(let i=0;i<this.projectUnitUsers.length;i++){
        if(this.projectUnitUsers[i].projectId==row.projectId){
          data = this.projectUnitUsers[i].data;
        }
      }
      data.forEach((item) => {
        item.userinfoList.forEach((u) => {
          if (u.phonenumber == val) {
            row.recheckSend = u.nickName + " [" + u.jobTypeName + "] ";
          }
        });
      });
    }
  }
};
</script>
<style lang="scss">
.el-upload--picture-card{
  width: 100px !important;
  height: 100px !important;
  line-height: 100px !important;
}
.el-upload-list--picture-card .el-upload-list__item{
  width: 100px !important;
  height: 100px !important;
}
.bt2{
  padding-left: 0px !important;
  margin-left: 0px !important;
}
</style>