<template>
  <div class="app-container">
    <el-card>
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
        <el-form-item label="巡查时间" prop="timeRange">
          <el-date-picker
            v-model="queryParams.timeRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="巡查点位" prop="patrolLocation">
          <el-input
            v-model="queryParams.patrolLocation"
            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-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="['app:quality:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDeleteAll"
            v-hasPermi="['app:quality:remove']"
          >删除</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </el-card>
    <br>
    <el-card>
      <el-table border stripe height="600" v-loading="loading" ref="multipleTable" :data="disposalList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"  />
        <!--  <el-table-column label="ID"  prop="id" width="80" />  -->
        <el-table-column label="巡查时间"  prop="patrolTime" />
        <el-table-column label="巡查点位"  prop="patrolLocation" />
        <el-table-column label="巡查内容"  width="300">
          <template slot-scope="scope">
            <div v-for="(item, i) in scope.row.contentList" :key="i">{{item}}</div>
          </template>
        </el-table-column>
        <el-table-column label="异常情况描述"  prop="abnormalCondition" />
        <el-table-column label="处置方式"  prop="dealMethod" />
        <el-table-column label="处置结果"  prop="dealResult" />
        <el-table-column label="巡查人"  prop="patrolUser" />
        <el-table-column label="操作" width="180"  class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleView(scope.row)"
            >查看</el-button>
<!--            <el-button-->
<!--              size="mini"-->
<!--              type="text"-->
<!--              icon="el-icon-edit"-->
<!--              @click="handleUpdate(scope.row)"-->
<!--              v-hasPermi="['app:quality:edit']"-->
<!--              style="margin-right: 10px"-->
<!--            >修改</el-button>-->
            <el-popconfirm
              v-hasPermi="['app:quality:remove']"
              :title="'是否确认删除所选数据项？'"
              @confirm="handleDelete(scope.row)"
            >
              <el-button
                size="mini"
                type="text"
                slot="reference"
                icon="el-icon-delete"
              >删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改死淘处理方式对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="550px" append-to-body>
      <el-form ref="form" label-position="left" :model="form" :rules="rules" :disabled="isView" label-width="100px">
        <el-form-item label="巡查时间" prop="patrolTime">
          <el-date-picker
            style="width: 100%"
            v-model="form.patrolTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="巡查点位" prop="patrolLocationArr">
          <!-- <el-input v-model="form.patrolLocation" type="textarea" :autosize="{ minRows: 2 }" axlength="50" show-word-limit  placeholder="请输入巡查点位" />
         -->
          <el-select v-model="form.patrolLocationArr" multiple clearable style="width:100%"  placeholder="请选择巡查点位">
            <el-option
              v-for="item in workList"
              :key="item.id"
              :label="item.pointName"
              :value="item.pointName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="巡查内容" prop="patrolContentArr">
          <el-select v-model="form.patrolContentArr" multiple clearable style="width:100%" placeholder="请选择巡查内容">
            <el-option
              v-for="(item, i) in contentArr"
              :key="i"
              :value="item"
              :label="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="异常情况描述" prop="abnormalCondition">
          <el-input type="textarea" :autosize="{ minRows: 2 }"   v-model="form.abnormalCondition" maxlength="50" show-word-limit :placeholder="isView ? '' : '请输入异常情况描述'" />
        </el-form-item>
        <el-form-item label="处置方式" prop="dealMethod">
          <el-input type="textarea" :autosize="{ minRows: 2 }"   v-model="form.dealMethod" maxlength="50" show-word-limit :placeholder="isView ? '' : '请输入处置方式'" />
        </el-form-item>
        <el-form-item label="处置结果" prop="dealResult">
          <el-input v-model="form.dealResult" type="textarea" :autosize="{ minRows: 2 }"  maxlength="50" show-word-limit :placeholder="isView ? '' : '请输入处置结果'" />
        </el-form-item>
        <el-form-item label="巡查人" prop="patrolUser">
          <el-input v-model="form.patrolUser" placeholder="请输入巡查人" maxlength="50" show-word-limit />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="!isView">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getQualityPage, getQualityDetail, addQualityPage, editQualityPage, delQualityPage } from "../../../api/app/quality";
import { formatDate } from "../../../utils";
import { required } from "../../../utils/formRules";
import {getUserProfile} from "../../../api/system/user";
import { getPtList } from "../../../api/app/pt";

export default {
  name: "",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      disposalList: [],
      // 弹出层标题
      title: "",
      isView:false,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        timeRange: null,
        patrolLocation: null,
        startTime: null,
        endTime: null
      },
      pickerOptions: {
        disabledDate(time) {
          // 获取当前日期
          const today = new Date();
          today.setHours(0, 0, 0, 0); // 将时间设置为当天的 00:00:00

          // 禁用今天之后的日期
          return time.getTime() > today.getTime();
        }
      },
      // 表单参数
      form: {
        abnormalCondition: '无异常',
        dealMethod: '无',
        dealResult: '环境整洁',
        id: null,
        patrolContent: null,
        patrolContentArr: [],
        patrolLocation: null,
        patrolLocationArr:[],
        patrolTime: formatDate(new Date()),
        patrolUser: null,
        patrolList: []
      },
      rules: {
        patrolTime: [required('巡查时间不能为空')],
        patrolLocationArr: [required('巡查点位不能为空')],
        patrolContentArr: [required('巡查内容不能为空')],
        patrolUser: [required('巡查人不能为空')],
      },
      user: {},
      workList:[],
      contentArr: [],
    }
  },
  watch: {
    "queryParams.timeRange": {
      handler(newVal) {
        if (newVal) {
          this.queryParams.startTime = newVal[0]
          this.queryParams.endTime = newVal[1]
        } else {
          this.queryParams.startTime = null
          this.queryParams.endTime = null
        }
      },
      deep: true
    },
    "form.patrolLocationArr": {
      handler(newVal) {
        if(newVal) {
          this.contentArr = []
          if(this.form.id === null) {
            this.form.patrolContentArr = []
          }
          let arr = []
          for(let i = 0; i < this.workList.length; i++) {
            for(let j = 0; j < newVal.length; j++) {
              if(this.workList[i].pointName === newVal[j]) {
                let list = this.workList[i].contentText ? this.workList[i].contentText.split(';') : []
                arr = arr.concat(list)
              }
            }
          }
          this.contentArr = arr
        }
      },
      deep: true
    },
    "form.patrolContentArr": {
      handler(newVal) {
        if(newVal) {
          let arr = this.workList.filter(item => this.form.patrolLocationArr.includes(item.pointName))
            .map(item => {
              // 对每个筛选出的项处理value
              const valueArray = item.contentText.split(';').filter(val => val !== ''); // 分割value并过滤空值
              const filteredValues = valueArray.filter(val => newVal.includes(val)); // 筛选出在arr2中的值
              const content = filteredValues.join(';') + (filteredValues.length > 0 ? ';' : ''); // 重新拼接并添加分号
              return {
                name: item.pointName,
                content: content
              };
            })
          this.form.patrolList = JSON.stringify(arr)
        }
      },
      deep: true
    }
  },
  created() {
    this.getUser()
    this.getList();
    this.getWorkshop();
  },
  methods: {
    //获取车间点位
    getWorkshop() {
      getPtList({}).then(res=> {
        this.workList = res.data
      })
    },
    /** getUser **/
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.form.patrolUser = response.data.nickName
      });
    },
    /** 查询检验项目列表 */
    getList() {
      getQualityPage(this.queryParams).then(res => {
        res.data.records.forEach(item => {
          item.contentList = item.patrolContent ? item.patrolContent.split(';') : [];
        })
        this.disposalList = res.data.records;
        this.total = res.data.total;
        this.loading = false;
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        timeRange: null,
        patrolLocation: null,
        startTime: null,
        endTime: null
      }
      // 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.isView = false;
      this.title = "添加质量巡查";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      let params = {
        id: id
      }
      getQualityDetail(params).then(res => {
        this.form = res.data;
        let patrolLocationArr = this.form.patrolLocation.split(",");
        this.$set(this.form,"patrolLocationArr",patrolLocationArr)
        let patrolContentArr = this.form.patrolContent.split(';');
        this.form.patrolContentArr = patrolContentArr
        console.log(this.form)
        this.open = true;
        this.isView = false;
        this.title = "修改质量巡查";
      })
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      const id = row.id;
      let params = {
        id: id
      }
      getQualityDetail(params).then(res => {
        this.form = res.data;
        let patrolLocationArr = this.form.patrolLocation.split(",");
        this.$set(this.form,"patrolLocationArr",patrolLocationArr)
        let patrolContentArr = this.form.patrolContent.split(';');
        this.form.patrolContentArr = patrolContentArr
        this.open = true;
        this.isView = true;
        this.title = "查看现场巡查";
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        abnormalCondition: '无异常',
        dealMethod: '无',
        dealResult: '环境整洁',
        id: null,
        patrolContent: null,
        patrolContentArr: [],
        patrolLocation: null,
        patrolLocationArr:[],
        patrolTime: formatDate(new Date()),
        patrolUser: this.user.nickName,
        patrolList: []
      };
      this.resetForm("form");
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.patrolLocation = this.form.patrolLocationArr.join(",");
          this.form.patrolContent = this.form.patrolContentArr.join(';');
          if (this.form.id != null) {
            // 编辑
            editQualityPage(this.form).then(res => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            })
          } else {
            // 新增
            addQualityPage(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id;
      let params = {
        ids: ids
      }
      delQualityPage(params).then(res => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      })
    },
    /** 删除按钮操作 */
    handleDeleteAll() {
      const ids = this.ids;
      this.$modal.confirm('是否确认删除所选数据项？').then(() => {
        let params = {
          ids: ids.join(',')
        }
        delQualityPage(params).then(res => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
          this.$refs.multipleTable.clearSelection();
        })
      })
    }
  }
}
</script>

<style scoped lang="scss">

</style>
