<template>
  <div class="app-container">
    <el-row :gutter="6">
      <el-col :span="8">
        
        <el-card>
          <div slot="header">
        <span>涉及组织</span>
      </div>
          <el-button type="primary" @click="dialogVisibles = true" size="small" v-if="checkPermission(['inspecttask_update'])"
            >增加组织</el-button
          >
          <el-table
            :data="recordList"
            border
            fit
            stripe
            highlight-current-row
            style="margin-top:4px"
            @row-click="deptClick"
            max-height="300"
          >
            <el-table-column label="组织名称">
              <template slot-scope="scope">
                {{ scope.row.dept__name }}
              </template>
            </el-table-column>
            <el-table-column label="检查状态">
              <template slot-scope="scope">
                {{ scope.row.state }}
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                
                <el-link
                  type="warning"
                  v-if="scope.row.state == '待检查'"
                  @click="handleStartup(scope)"
                  >开始检查</el-link>

                <el-link
                  type="primary"
                  v-if="scope.row.state == '检查中'"
                  @click="handleCheckup(scope)">组长提交</el-link>
                <el-link type="danger" @click="handleDelete(scope)" v-if="checkPermission(['inspecttask_update'])"
                  >删除</el-link
                >
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        <el-card style="margin-top:4px">
          <div slot="header">
        <span>检查组成员</span>
      </div>
          <el-button type="primary" @click="handleCreateMember" size="small" v-if="checkPermission(['inspecttask_update'])"
            >增加成员</el-button
          >
          <el-table
            :data="members"
            border
            fit
            stripe
            highlight-current-row
            style="margin-top:4px"
            max-height="600"
          >
            <el-table-column label="成员名">
              <template slot-scope="scope">
                {{ scope.row.member__name }}
              </template>
            </el-table-column>
            <el-table-column label="成员类型">
              <template slot-scope="scope">
                {{ scope.row.type }}
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-link type="danger" @click="handleDeleteMember(scope)" v-if="checkPermission(['inspecttask_update'])"
                  >删除</el-link
                >
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="16">
           <el-card>
          <div slot="header">
        <span>检查详情</span>
      </div>
          <el-button type="primary" @click="dialogFormVisible = true" size="small"
            >指派任务</el-button
          >
          <el-table
            :data="inspectitemList"
            border
            fit
            stripe
            highlight-current-row
            style="margin-top:4px"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55"> </el-table-column>

            <el-table-column label="检查事项" >
              <template slot-scope="scope">
                {{ scope.row.item_.sortnum }}.{{ scope.row.item_.name }}
              </template>
            </el-table-column>
            <el-table-column label="检查类型" >
              <template slot-scope="scope">
                {{ scope.row.item_.type }}
              </template>
            </el-table-column>

            <el-table-column label="检查人" >
              <template slot-scope="scope" v-if="scope.row.checker_">
                {{ scope.row.checker_.name }}
              </template>
            </el-table-column>
            <el-table-column label="检查状态" >
              <template slot-scope="scope">
                <span v-if="scope.row.checked" style="color: green"
                  >已检查</span
                >
                <span v-else style="color: blue">未检查</span>
              </template>
            </el-table-column>

            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-link @click="handleCheck(scope)" type="primary" v-if="nowDept.state=='检查中'">检查</el-link>
                <el-link @click="handleCheckDetail(scope)">详情</el-link>
              </template>
            </el-table-column>
          </el-table>
           </el-card>
      </el-col>
    </el-row>
      <el-dialog
            :visible.sync="dialogFormVisible"
            title="指派人员"
          >
            <el-form
              ref="Forms"
              :model="mbersData"
              label-width="80px"
              label-position="right"
            >
              <el-form-item label="检查人" prop="checker">
                <el-select
                  v-model="mbersData.checker"
                  style="width: 100%"
                  default-first-option
                  placeholder="请选择检查人"
                >
                  <el-option
                    v-for="item in members"
                    :key="item.member"
                    :label="item.member__name"
                    :value="item.member"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <div style="text-align: right">
              <el-button type="danger" @click="dialogFormVisible = false"
                >取消</el-button
              >
              <el-button type="primary" @click="sendconfirm('Forms')"
                >确认</el-button
              >
            </div>
          </el-dialog>
                <el-dialog
            :visible.sync="createMemberDg"
            title="增加成员"
          >
            <el-form
              ref="Forms"
              :model="memberForm"
              label-width="80px"
              label-position="right"
            >
              <el-form-item label="成员" prop="member">
                <el-select
                  v-model="memberForm.member"
                  style="width: 100%"
                  default-first-option
                  placeholder="请选择成员"
                >
                  <el-option
                    v-for="item in memberOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
<el-form-item label="成员类型" prop="type">
              <el-radio-group v-model="memberForm.type">
    <el-radio label="组员">组员</el-radio>
    <el-radio label="组长">组长</el-radio>
  </el-radio-group>
</el-form-item>
            </el-form>
            <div style="text-align: right">
              <el-button type="danger" @click="createMemberDg = false"
                >取消</el-button
              >
              <el-button type="primary" @click="confirmMember"
                >确认</el-button
              >
            </div>
          </el-dialog>
          <el-dialog :visible.sync="dialogVisibles">
            <el-form
              ref="Formss"
              label-width="80px"
              label-position="right"
              :model="inspectDept"
            >
              <el-form-item label="选择组织" prop="leader">
                <el-cascader :options="deptOptions"   :props="{ checkStrictly: true,emitPath:false }" ref="demoCascader"  v-model="inspectDept.dept"></el-cascader>
               
              </el-form-item>
            </el-form>
            <div style="text-align: right">
              <el-button type="danger" @click="dialogVisibles = false"
                >取消</el-button
              >
              <el-button type="primary" @click="addDept('Formss')"
                >确认</el-button
              >
            </div>
          </el-dialog>
          <el-drawer
            title="任务详情"
            
            :visible.sync="dialog"
            direction="ltr"
            ref="drawer"
          >
            <div class="app-container">
              <el-form :model="inspectrecord" :disabled="readonly">
                <el-form-item
                  v-if="inspectrecord.item_"
                >
                  {{ inspectrecord.item_.cate_name }}
                  <el-tag effect="plain">{{ inspectrecord.item_.type }}</el-tag>
                </el-form-item>
                <el-form-item
                  label="检查事项"
                  v-if="inspectrecord.item_"
                >
                  {{ inspectrecord.item_.sortnum }}.{{ inspectrecord.item_.name }}
                </el-form-item>
                <el-form-item
                  label="取证要求"
                  v-if="inspectrecord.item_"
                >
                  {{ inspectrecord.item_.require }}
                </el-form-item>
                <el-form-item label="检查结果">
                  <el-select
                    v-model="inspectrecord.result"
                    placeholder="请选择检查结果"
                  >
                    <el-option label="发现" value="发现"></el-option>
                    <el-option label="未发现" value="未发现"></el-option>
                    <el-option label="不适用" value="不适用"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="检查说明" >
                  <el-input
                    type="textarea"
                    maxlength="-1"
                    v-model="inspectrecord.note"
                    autocomplete="off"
                  ></el-input>
                </el-form-item>
                <el-form-item label="文件列表" >
                  <el-upload
                    :action="upUrl"
                    :before-upload="beforeUpload"
                    :on-success="handleUpSuccess"
                    :headers="upHeaders"
                    ref="upload"
                    multiple
                    accept="image/*,.ppt,.pdf,.doc,.docx,.xls,.xlsx"
                  >
                    <el-button size="small" type="primary">上传文件</el-button>
                  </el-upload>
                </el-form-item>
                <div
                  v-for="(item, index) in fileList"
                  v-bind:key="item.id"
                  style="margin-top: 2px"
                >
                  <i
                    class="el-icon-delete"
                    @click="deleteFile(index)"
                    style="color: red"
                  ></i>
                  <el-link :href="item.path" target="_blank" type="primary">{{
                    item.name
                  }}</el-link>
                </div>
              </el-form>
              <div style="float: right;margin-top:4px;padding-right:4px" v-if="!readonly">
                <el-button @click="cancelForm" type="danger">取 消</el-button>
                <el-button
                  type="primary"
                  @click="handleClose"
                  :loading="loading"
                  >{{ loading ? "提交中 ..." : "确 定" }}</el-button
                >
              </div>
            </div>
          </el-drawer>
       
  </div>
</template>
<script>
import {
  getsubinspecttaskdep,
  getinspectrecordlist,
  updateinspectrecord,
  getinspectrecord,
  upinspectdept,
  gettaskdepstart,
  addappoint,
} from "@/api/subinspecttask";

import { genTree } from "@/utils";
import { getOrgList } from "@/api/org";
import { getUserList } from "@/api/user";
import { deleteInspectdept, creatInspectdept } from "@/api/qualityinspect";
import { getInspectTeamList, createInspectTeam, deleteInspectTeam} from "@/api/inspectteam"
import { upUrl, upHeaders } from "@/api/file";
import Pagination from "@/components/Pagination";
import checkPermission from "@/utils/permission";

const mbersData = {
  checker: "",
};
const inspectdept = {
  dept: null,
};
const memberForm = {
  member:null,
  type:'组员'
}
export default {
  components: { Pagination },

  data() {
    return {
      listLoading: true,
      dialog: false,
      recordList: [],
      dialogVisibles: false,
      dialogFormVisible: false,
      inspectitemList: [],
      deptOptions: [],
      members: [],
      inspectDept: inspectdept,
      dialogType: "new",
      listQuery: {},
      inspectrecord: null,
      require: "",
      ids: [],
      mbersData: mbersData,
      upHeaders: upHeaders(),
      upUrl: upUrl(),
      fileList: [],
      table: false,
      dialog: false,
      loading: false,
      recordid: null,
      inspectrecord: {
        id: null,
        note: "",
        result: "",
        imgs: [],
      },
      formLabelWidth: "80px",
      timer: null,
      memberOptions:[],
      createMemberDg:false,
      memberForm:{},
      nowDept:{},
      readonly:false
    };
  },
  created() {
    this.id = this.$route.params.id;
    // this.members = this.$route.params.members;
    this.getOrgList();
    this.getsubinspecttaskdep(); //主任务信息
    this.getinspectteam();
    this.getUserList();//组员
  },

  methods: {
    checkPermission,

    //巡检的公司
    getsubinspecttaskdep() {
      getsubinspecttaskdep(this.id).then((res) => {
        this.recordList = res.data;
      });
    },
    //巡查组成员
    getinspectteam(){
      getInspectTeamList({pageoff:true, subtask:this.id}).then(res=>{
        this.members = res.data
      })
    },
    //可选择的成员
    getUserList() {
      getUserList({pageoff:true, roles__name:'质量巡查成员'}).then((res) => {
        this.memberOptions = res.data
      });
    },

    //组织列表
    getOrgList() {
      getOrgList({ can_supervision: true }).then((res) => {
        this.deptOptions = genTree(res.data);
      });
    },
    //点击组织弹出检查项
    deptClick(row) {
      this.listLoading2 = true;
      this.listQuery = { pageoff: true, subtask: row.subtask, dept: row.dept };
      this.nowDept=row
      this.getinspectrecordlist();
    },

    //点击组织弹出清单
    getinspectrecordlist() {
      getinspectrecordlist(this.listQuery).then((res) => {
        this.inspectitemList = res.data;
      });
    },
  
    handleCheck(scope) {
      this.readonly = false;
      this.dialog = true;

      this.recordid = scope.row.id;
      this.fileList = [];
      getinspectrecord(this.recordid).then((res) => {
        this.inspectrecord = res.data;
        for (var i = 0; i < this.inspectrecord.imgs_.length; i++) {
          this.fileList.push({
            id: this.inspectrecord.imgs_[i].id,
            name: this.inspectrecord.imgs_[i].name,
            path: this.inspectrecord.imgs_[i].path,
          });
        }
      });
    },
    handleCheckDetail(scope) {
      this.readonly = true;
      this.dialog = true;

      this.recordid = scope.row.id;
      this.fileList = [];
      getinspectrecord(this.recordid).then((res) => {
        this.inspectrecord = res.data;
        for (var i = 0; i < this.inspectrecord.imgs_.length; i++) {
          this.fileList.push({
            id: this.inspectrecord.imgs_[i].id,
            name: this.inspectrecord.imgs_[i].name,
            path: this.inspectrecord.imgs_[i].path,
          });
        }
      });
    },
    handleUpSuccess(res, file, filelist) {
      this.fileList.push({
        id: res.data.id,
        name: res.data.name,
        path: res.data.path,
      });
      this.handleRemove(file);
    },
    handleRemove(file) {
      // 实现删除文件
      let fileList = this.$refs.upload.uploadFiles;
      let index = fileList.findIndex((fileItem) => {
        return fileItem.uid === file.uid;
      });
      fileList.splice(index, 1);
    },
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 50;
      if (!isLt2M) {
        this.$message.error("单文件不能超过50MB!");
      }
      return isLt2M;
    },
    deleteFile(index) {
      this.$confirm("确定删除该文件, 是否继续?", { type: "error" })
        .then(() => {
          this.fileList.splice(index, 1);
        })
        .catch((e) => {});
    },
    //提交结果
    handleClose(done) {
      if (this.loading) {
        return;
      }
      this.$confirm("确定提交？")
        .then((_) => {
          var files = [];
          for (var i = 0; i < this.fileList.length; i++) {
            files.push(this.fileList[i].id);
          }
          this.inspectrecord.imgs = files;
          this.inspectrecord.id = this.recordid;
          console.log(this.recordid);
          updateinspectrecord(this.recordid, this.inspectrecord).then((res) => {
            if (res.code >= 200) {
              this.getinspectrecordlist();
              this.getsubinspecttaskdep();
              this.dialog = false;
              this.$message.success("成功");
            }
          });
        })
        .catch((_) => {});
    },
    cancelForm() {
      this.loading = false;
      this.dialog = false;
      clearTimeout(this.timer);
    },
    //组长提交
    handleCheckup(scope) {
      upinspectdept(scope.row.id).then((res) => {
        this.$message.success("提交成功");
        this.getinspectrecordlist();
        this.getsubinspecttaskdep();
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //组长指派人员
    sendconfirm() {
      this.ids = [];

      const lengths = this.multipleSelection.length;
      for (let i = 0; i < lengths; i++) {
        this.ids.push(this.multipleSelection[i].id);
      }

      this.mbersData.records = this.ids;
      console.log(this.mbersData);
      addappoint(this.mbersData).then((res) => {
        this.dialogFormVisible = false;
        this.getinspectrecordlist();
        this.$message.success("成功");
      });
    },
    //组长提交开始检查
    handleStartup(scope) {
      gettaskdepstart(scope.row.id).then((res) => {
        this.$message.success("提交成功");
        this.getinspectrecordlist();
        this.getsubinspecttaskdep();
      });
    },
    handleCreateMember(){
      this.memberForm = Object.assign({}, memberForm);
      this.memberForm.subtask = this.id;
      this.createMemberDg = true
    },
    confirmMember(){
      if(this.memberForm.member && this.memberForm.type){
        createInspectTeam(this.memberForm).then(res=>{
          this.$message.success("提交成功");
          this.getinspectteam()
          this.createMemberDg = false
        })
      }
    },
    handleDelete(scope) {
      this.$confirm("确认删除?", "警告", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "error",
      })
        .then(async () => {
          await deleteInspectdept(scope.row.id);
          this.getsubinspecttaskdep();
          this.$message.success("成功");
        })
        .catch((err) => {
          console.error(err);
        });
    },
    handleDeleteMember(scope) {
      this.$confirm("确认删除?", "警告", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "error",
      })
        .then(async () => {
          await deleteInspectTeam(scope.row.id);
          this.getinspectteam();
          this.$message.success("成功");
        })
        .catch((err) => {
          console.error(err);
        });
    },
    //增加待巡检的公司
    addDept() {
      console.log(this.inspectDept);
      this.inspectDept.subtask = this.$route.params.id;

      creatInspectdept(this.inspectDept).then((res) => {
        if (res.code >= 200) {
          this.getsubinspecttaskdep();
          this.dialogVisibles = false;
          this.$message.success("成功");
        }
      });
    },
  },
};
</script>