<template>
  <div class="app-container">
    <div ref="sousuH">
      <!-- 搜索工作栏 -->
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="指令标题" prop="comTitle">
          <el-input v-model="queryParams.comTitle" placeholder="请输入指令标题" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <!-- <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
            <el-option v-for="dict in this.getDictDatas(DICT_TYPE.COMMON_STATUS)" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="指令类型" prop="comType">
          <el-select v-model="queryParams.comType" placeholder="请选择指令类型" clearable size="small">
            <el-option v-for="dict in this.getDictDatas(DICT_TYPE.INSPECTITEM_TYPE)" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @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="['backend:com-info:create']">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
            :loading="exportLoading" v-hasPermi="['backend:com-info:export']">导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </div>
    <!-- 列表 -->
    <el-table v-loading="loading" :data="list" :height="list.length ? tableHeight : 'auto'">
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="指令标题" align="center" prop="comTitle" />
      <el-table-column label="发布状态" align="center" prop="comStatus">
        <template slot-scope="{row}">
          <div>{{ row.comStatus == 1 ? '已发布' : '未发布' }}</div>
        </template>
      </el-table-column>
      <el-table-column label="指令内容" align="center">
        <template slot-scope="scope">
          <div v-html="scope.row.comContent"></div>
        </template>
      </el-table-column>
      <!-- <el-table-column label="状态" align="center" prop="status">
        <template v-slot="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column> -->
      <el-table-column label="指令类型" align="center" prop="comType">
        <template v-slot="scope">
          <dict-tag :type="DICT_TYPE.INSPECTITEM_TYPE" :value="scope.row.comType" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200">
        <template v-slot="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['backend:com-info:update']">修改</el-button>
          <!-- <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                                v-hasPermi="['backend:task-info:delete']">删除</el-button> -->
          <el-dropdown @command="(command) => handleCommand(command, scope.$index, scope.row)">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleDelete" size="mini" type="text" icon="el-icon-delete"
                v-hasPermi="['backend:com-info:delete']">删除</el-dropdown-item>
              <el-dropdown-item command="handleSelectedOrg" size="mini" type="text"
                icon="el-icon-circle-check">已下达指令人员</el-dropdown-item>
              <el-dropdown-item command="handleOrg" size="mini" type="text"
                icon="el-icon-circle-check">下达单位</el-dropdown-item>
              <el-dropdown-item command="handPublish" size="mini" type="text" v-if="scope.row.comStatus == 0"
                icon="el-icon-circle-check">发布</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <!-- <el-button size="mini" type="text" icon="el-icon-help" @click="lookMes(scope.row)">查看详情</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="500px" v-dialogDrag append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="指令标题" prop="comTitle">
          <el-input v-model="form.comTitle" placeholder="请输入指令标题" />
        </el-form-item>
        <el-form-item label="指令类型" prop="comType">
          <el-select v-model="form.comType" placeholder="请选择指令类型" style="width: 100%;">
            <el-option v-for="dict in this.getDictDatas(DICT_TYPE.INSPECTITEM_TYPE)" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="指令内容">
          <editor v-model="form.comContent" :min-height="192" />
        </el-form-item>
        <el-form-item label="附件id" prop="attId">
          <fileUpload v-model="form.attId" />
        </el-form-item>

        <!-- <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status" style="width: 100%;">
            <el-radio v-for="dict in this.getDictDatas(DICT_TYPE.COMMON_STATUS)" :key="dict.value"
              :label="parseInt(dict.value)">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <!-- <el-form-item label="单位类别">
                    <el-select v-model="form.orgType" multiple placeholder="请选择单位类别">
                      <el-option v-for="dict in this.getDictDatas(DICT_TYPE.COMPANY_inspectitem_kind)" :key="dict.value"
                        :label="dict.label" :value="dict.value" />
                    </el-select>
                  </el-form-item> -->
        <!-- <el-form-item label="单位">
                    <el-input clear @focus="handleFocus" @clear="handleClear" placeholder="请选择单位" v-model="orgList"
                        clearable>
                        <template slot="append">
                            <i title="选择" @click="handleChoice" style="cursor:pointer;" class="el-icon-plus"></i>
                        </template>
                    </el-input>
                </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 分配分管单位 -->
    <el-dialog title="分配分管单位" :visible.sync="openOrg" width="85vw" append-to-body v-if="openOrg">
      <choiceSelect ref="choiceSelect" :userId="form.id" :type="'comInfo'"></choiceSelect>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitOrg">确 定</el-button>
        <el-button @click="cancelOrg">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 已选择分管单位 -->
    <el-dialog title="已下达指令人员" :visible.sync="openSelectedOrg" width="85vw" append-to-body v-if="openSelectedOrg">
      <handleSelectedOrg ref="choiceSelect" :userId="form.id" :type="'comInfo'"></handleSelectedOrg>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="openSelectedOrg = false">关 闭</el-button>
      </div>
    </el-dialog>
    <el-dialog title="已分配单位" :visible.sync="comInfoOrg" width="85vw" append-to-body>
      <handleSelectedOrg ref="choiceSelect" :userId="form.id" :type="'comInfoOrg'"></handleSelectedOrg>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="comInfoOrg = false">关 闭</el-button>
      </div>
    </el-dialog>
    <!-- 查看下达的单位 -->
    <el-dialog title="下达单位" :visible.sync="downHouse" width="50%">
      <!-- <el-button plain icon="el-icon-download" size="mini" @click="nowExcel" type="warning" style="margin-bottom: 10px;">导出</el-button> -->
      <el-table :data="downList">
        <el-table-column label="单位名称" align="center" prop="id" />
        <el-table-column label="单位地址" align="center" prop="meetingId" />
        <el-table-column label="是否已读" align="center" prop="ppName" />
        <!-- <el-table-column label="参会人联系电话" align="center" prop="ppTel" width="200" />
        <el-table-column label="参会人单位id" align="center" prop="orgId" />
        <el-table-column label="参会人职务" align="center" prop="ppDuty" /> -->
      </el-table>
      <!-- <pagination v-show="totals > 0" :total="totals" page.sync="1" limit.sync="10" @pagination="getList" /> -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="downHouse = false">取 消</el-button>
        <el-button type="primary" @click="downHouse = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { createComInfo, updateComInfo, deleteComInfo, getComInfo, getComInfoPage, exportComInfoExcel, broadCominfo, setupComuser, getselfComuser,getNewsList } from "@/api/backend/comInfo"
import Editor from '@/components/Editor'
import { DICT_TYPE, getDictDatas } from "@/utils/dict";
import choiceSelect from '@/components/choiceSelect';
import FileUpload from '@/components/FileUpload'
import handleSelectedOrg from '@/components/handleSelectedOrg';
import { getTableHeight } from "@/utils/ruoyi.js";

export default {
  name: "ComInfo",
  components: {
    Editor, choiceSelect, handleSelectedOrg, FileUpload,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 指令信息列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        comTitle: null,
        comContent: null,
        status: null,
        comType: null,
      },
      // 表单参数
      form: {
        status: 0
      },
      // 表单校验
      rules: {
        status: [{ required: true, message: "状态不能为空", trigger: "blur" }],
        comTitle: [{ required: true, message: "请输入指令标题", trigger: "blur" }],
        comType: [{ required: true, message: "请输入指令类型", trigger: "blur" }],
      },
      // =======单位信息==========================
      // 是否显示弹出层（分管单位）
      openOrg: false,
      // 最终选择的单位信息列表
      alreadySelectedOrgList: [],
      orgList: '',
      tableHeight: "",
      // 已选择单位
      openSelectedOrg: false,
      orgType: undefined,
      downHouse: false,//查看人员
      totals: 0,
      downList:[],
      comInfoOrg:false
    }
  },
  mounted() {
    //挂载window.onresize事件(动态设置table高度)
    window.addEventListener('resize', () => {
      this.$nextTick(() => {
        if (this.$refs['sousuH']) {
          this.tableHeight = getTableHeight(this.$refs['sousuH'].clientHeight + 200)
        }
      })
    })
  },
  created() {
    this.getList()
    this.$nextTick(() => {
      this.tableHeight = getTableHeight(this.$refs['sousuH'].clientHeight + 200)
    })
  },
  methods: {

    // 更多操作
    handleCommand(command, index, row) {
      const id = row.id
      getComInfo(id).then(response => {
        this.form = response.data
      })
      switch (command) {
        case 'handleUpdate':
          this.handleUpdate(row);//修改客户信息
          break;
        case 'handleDelete':
          this.handleDelete(row);//红号变更
          break;
        case 'handleOrg':
          this.handleOrg(row);
          break;
        case 'handleSelectedOrg':
          this.handleSelectedOrg(row);
          break;
        case 'handPublish':
          this.handPublish(row);
          break;
        default:
          break;
      }
    },
    /** 查询列表 */
    getList() {
      this.loading = true
      // 执行查询
      getComInfoPage(this.queryParams).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.loading = false
      })
    },
    /** 取消按钮 */
    cancel() {
      this.open = false
      this.reset()
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        comTitle: undefined,
        comContent: undefined,
        attId: undefined,
        status: 0,
        comType: undefined,
        // orgType: undefined,
      }
      this.resetForm("form")
      this.orgList = ''
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加指令信息"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id
      getComInfo(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改指令信息"
      })
    },
    /** 提交按钮 */
    submitForm() {

      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return
        }
        // 修改的提交
        if (this.form.id != null) {
          updateComInfo(this.form).then((response) => {
            this.$modal.msgSuccess("修改成功")
            this.open = false
            this.getList()
          })
          return
        }
        // 添加的提交
        createComInfo(this.form).then((response) => {
          this.$modal.msgSuccess("新增成功")
          this.open = false
          this.getList()
        })
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id
      this.$modal
        .confirm('是否确认删除指令为"' + row.comTitle + '"的数据项?')
        .then(function () {
          return deleteComInfo(id)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess("删除成功")
        })
        .catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = { ...this.queryParams }
      params.pageNo = undefined
      params.pageSize = undefined
      // 执行导出
      this.$modal
        .confirm("是否确认导出所有指令?")
        .then(() => {
          this.exportLoading = true
          return exportComInfoExcel(params)
        })
        .then((response) => {
          this.$download.excel(response, "指令下达.xls")
          this.exportLoading = false
        })
        .catch(() => { })
    },

    /**
     * 选单位
     */
    // ========获取已选单位信息=============================================================

    // -========================================================
    // =========表单添加时选单位=================================================
    handleClear() {
      this.form.orgList = "";
    },
    handleFocus() {
      this.handleChoice();
    },
    handleChoice() {
      // 打开弹窗
      this.openOrg = true;
    },
    // ============操作区修改单位=====================================================
    // 单位信息表单重置
    Orgreset() {
      this.alreadySelectedOrgList = []
    },
    // 打开单位信息v弹窗
    handleOrg(row) {
      this.Orgreset()
      if (row.id) {
        this.form.id = row.id
      }
      // 打开弹窗
      this.openOrg = true;
    },

    // /============单位弹窗功能====================================================
    /** 单位信息确认按钮 */
    submitOrg() {
      this.alreadySelectedOrgList = this.$refs["choiceSelect"].confirmMSg()
      this.orgType = this.$refs["choiceSelect"].confirmoOrgTypeMSg()
      console.log('this.orgType :>> ', this.orgType);
      // 关闭弹窗
      this.openOrg = false;
      this.submitFormOrg(this.$refs["choiceSelect"].confirmMSg(), this.$refs["choiceSelect"].confirmoOrgTypeMSg())

    },

    // 取消按钮（分管单位）
    cancelOrg() {
      this.openOrg = false;
    },
    // ========用于form表单已存在alreadySelectedOrgList单位信息时保存============================

    submitFormOrg(alreadySelectedOrgList, orgType) {
      var orgIds = []
      alreadySelectedOrgList.map(i => {
        orgIds.push(i.dwid)
      })
      this.form.orgTypes = orgType
      this.form.orgIds = orgIds
      this.form.comId = this.form.id
      console.log('this.form :>> ', this.form.id, this.form);
      // =====================
      setupComuser(this.form).then(response => {
        // this.$modal.msgSuccess("分配角色成功");
      });
    },
    // ===============已分配单位列表========================
    handleSelectedOrg(row) {
      if (row.id) {
        this.form.id = row.id
      }
      // 打开弹窗
      this.openSelectedOrg = true;
    },
    lookMes(row) {
      if (row.id) {
        this.form.id = row.id
      }
      this.comInfoOrg=true
      // getNewsList({ ids: row.id }).then(res => {
      //   console.log(res.data[0].comBroadDOList, '111');
      //   this.downList = res.data[0].comBroadDOList
      //   this.downHouse = true
      // })
    },
    // -==========发布======================
    handPublish(row) {
      if (row.id) {
        broadCominfo({ comId: row.id }).then(response => {
          // this.$modal.msgSuccess("分配角色成功");

          this.getList()
        });
      }
    }

  },
}
</script>