<template>
  <div class="app-container">
    <el-row :gutter="10">
      <!--机构数据-->
      <!-- <el-col :span="4" :xs="24">
        <org-tree
          v-model="queryParams.orgId"
          @defaultKey="getDefaultKey"
          @checkChange="checkChange"
          @click="clickTreeNode"
          :defaultCheckSub="false"
          hangsheTree
        ></org-tree>
      </el-col> -->

      <el-col :span="24" :xs="24">
        <div class="main-right-box">
          <!--    搜索条件    -->
          <div class="main-search-box">
            <el-form
              :model="queryParams"
              ref="search"
              size="small"
              :inline="true"
              v-show="showSearch"
            >
              <el-form-item label="行社名称">
                <org-tree
                  v-model="queryParams.orgId"
                  @defaultKey="getDefaultKey"
                  @checkChange="checkChange"
                  @click="clickTreeNode"
                  :defaultCheckSub="false"
                  hangsheTree
                  ref="orgTree"
                ></org-tree>
              </el-form-item>
              <el-form-item prop="planType" label="任务类型">
                <el-select
                  prop="planType"
                  label="任务类型"
                  v-model="queryParams.planType"
                  placeholder="请选择任务类型"
                  clearable
                >
                  <el-option
                    v-for="dict in dict.type.resumption_plan_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item prop="resumptionRole" label="履职人员">
                <el-select
                  @visible-change="getRolesByOrg"
                  prop="resumptionRole"
                  label="履职人员"
                  v-model="queryParams.resumptionRole"
                  placeholder="请选择用户角色"
                  clearable
                >
                  <el-option
                    v-for="dict in resumptionRoles"
                    :key="dict.index"
                    :label="dict.roleName"
                    :value="dict.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item prop="planCycle" label="任务周期">
                <el-select
                  prop="planCycle"
                  label="任务周期"
                  v-model="queryParams.planCycle"
                  placeholder="请选择任务周期"
                  clearable
                >
                  <el-option
                    v-for="item in dict.type.resumption_plan_cycle"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="planStatus" label="任务状态">
                <el-select
                  prop="planStatus"
                  label="任务状态"
                  v-model="queryParams.planStatus"
                  placeholder="请选择任务状态"
                  clearable
                >
                  <el-option
                    v-for="item in dict.type.resumption_plan_status"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
                <!-- <el-switch v-model="queryParams.planStatus" active-value="1" inactive-value="0"></el-switch> -->
              </el-form-item>
              <el-form-item prop="planName" label="任务名称">
                <el-input
                  v-model="queryParams.planName"
                  :maxlength="50"
                  name="planName"
                  placeholder="请输入任务名称"
                  clearable
                />
              </el-form-item>

              <!-- <el-row :gutter="10" >
            <el-col :span="1.5"> </el-col>


          </el-row> -->
            </el-form>
            <el-row>
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="getList"
                >搜索</el-button
              >
              <el-button
                type="primary"
                icon="el-icon-refresh"
                size="mini"
                @click="resetQuery"
                >重置</el-button
              >
              <el-button
                type="primary"
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd()"
                v-hasPermi="['core:plan:edit']"
                >新增任务</el-button
              >
              <right-toolbar
                :showSearch.sync="showSearch"
                @queryTable="getList"
              ></right-toolbar>
            </el-row>
          </div>
          <!--    按纽    -->

          <el-table
            border
            height="594"
            size="small"
            v-loading="loading"
            :data="pageData"
            @selection-change="handleSelectionChange"
            row-key="id"
          >
            <el-table-column
              label="序号"
              fixed
              type="index"
              align="center"
              width="80px"
              v-if="columns[0].visible"
            ></el-table-column>
            <el-table-column
              prop="planName"
              label="任务名称"
              width="250px"
              :show-overflow-tooltip="true"
              v-if="columns[1].visible"
            ></el-table-column>
            <el-table-column
              prop="planType"
              label="任务类型"
              align="center"
              width="180px"
              v-if="columns[2].visible"
            >
              <template slot-scope="r"
                >{{
                  getLabel(dict.type.resumption_plan_type, `${r.row.planType}`)
                }}
              </template>
            </el-table-column>
            <el-table-column
              prop="planCreateOrgName"
              label="创建机构"
              align="center"
              width="180px"
              v-if="columns[3].visible"
            >
              <!-- <template slot-scope="r"
              >{{ getLabel(dict.type.sys_org_type, r.row.execOrgType) }}
            </template> -->
            </el-table-column>
            <el-table-column
              prop="planOfOrgName"
              label="行社名称"
              align="center"
              width="180px"
              v-if="columns[4].visible"
            ></el-table-column>

            <el-table-column
              prop="execOrgType"
              label="机构类型"
              align="center"
              width="180px"
              v-if="columns[5].visible"
            >
              <template slot-scope="r"
                >{{ getLabel(dict.type.sys_org_type, `${r.row.execOrgType}`) }}
              </template>
            </el-table-column>

            <el-table-column
              prop="roleNames"
              label="履职人员"
              align="center"
              width="180px"
              v-if="columns[6].visible"
            ></el-table-column>
            <el-table-column
              prop="planCycle"
              label="任务周期"
              align="center"
              width="180px"
              v-if="columns[7].visible"
            >
              <template slot-scope="r"
                >{{
                  getLabel(
                    dict.type.resumption_plan_cycle,
                    `${r.row.planCycle}`
                  )
                }}
              </template>
            </el-table-column>

            <el-table-column
              prop="planExec"
              label="任务时间"
              align="center"
              width="180px"
              v-if="columns[8].visible"
            >
              <template slot-scope="r"
                >{{
                  getLabel(dict.type.resumption_plan_exec, `${r.row.planExec}`)
                }}
              </template>
            </el-table-column>
            <el-table-column
              prop="count"
              label="任务次数"
              align="center"
              width="180px"
              v-if="columns[7].visible"
            ></el-table-column>
            <el-table-column
              prop="planStatus"
              label="任务状态"
              align="center"
              width="180px"
              v-if="columns[10].visible"
            >
              <template slot-scope="r"
                >{{
                  getLabel(
                    dict.type.resumption_plan_status,
                    `${r.row.planStatus}`
                  )
                }}
              </template>
            </el-table-column>
            <el-table-column
              prop="updateName"
              label="修改人"
              align="center"
              width="180px"
              v-if="false"
            ></el-table-column>

            <el-table-column fixed="right" width="210" label="操作">
              <template slot-scope="r">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-arrow-down"
                  v-if="showPublish(r.row)"
                  @click="showDialogDistribute(r.row)"
                  v-hasPermi="['core:plan:distribute']"
                  >下发</el-button
                >
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-top-left"
                  v-if="showWithDraw(r.row)"
                  @click="chhuile(r.row)"
                  v-hasPermi="['core:plan:distribute']"
                  >撤回</el-button
                >
                <el-button
                  v-if="eqOrg(r.row)"
                  size="mini"
                  type="text"
                  icon="el-icon-edit-outline"
                  @click="onEdit(r.row.id)"
                  v-hasPermi="['core:plan:edit']"
                  >编辑</el-button
                >
                <el-button
                  v-if="showDelete(r.row)"
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="onDel(r.row)"
                  v-hasPermi="['core:plan:delete']"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </div>
      </el-col>
    </el-row>
    <dialog-edit
      ref="editDialog"
      @success="getList()"
      :orgTypeOptions="orgTypeOptions"
      :ruleTypeOptions="dict.type.rule_type"
    ></dialog-edit>
    <DialogDistribute ref="dialogDistribute" @select="sel"></DialogDistribute>
    <DialogThreeState ref="DialogThreeState"> </DialogThreeState>
  </div>
</template>

<script>
import DialogDistribute from "@/views/resumption/plan/distribute.vue";
import OrgTree from "@/components/orgTree/orgQuerySelector.vue";
import { mapState, mapMutations, mapGetters } from "vuex";
import DialogEdit from "./dialog.edit";
import * as api from "@/api/resumption/plan";
import { statusOptions, getLabel } from "./../../commonOption";
import { allRole } from "@/api/system/role";
import DialogThreeState from "@/components/message/threeStateMessageBox.vue";
export default {
  name: "resumptionplan",
  dicts: [
    "sys_org_type",
    "rule_type",
    "resumption_plan_type",
    "resumption_plan_cycle",
    "resumption_plan_status",
    "resumption_plan_exec",
  ],
  components: {
    DialogEdit,
    OrgTree,
    DialogDistribute,
    DialogThreeState,
  },
  data() {
    const { params, query } = this.$route;
    return {
      isShow: false,
      loading: false,
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      resumptionRoles: [],
      total: 0,
      queryParams: {
        orgId: null,
        planType: null,
        resumptionRole: null,
        planCycle: null,
        planStatus: null,
        planName: null,
        pageNum: 1,
        pageSize: 10,
        checkSub: false,
        roleList: [],
        ...query,
      },
      pageData: [],
      // 列信息
      columns: [
        { key: 0, label: `序号`, visible: true },
        { key: 1, label: `计划名称`, visible: true },
        { key: 2, label: `计划类型`, visible: true },
        { key: 3, label: `计划创建机构`, visible: true },
        { key: 4, label: `计划所属机构`, visible: true },
        { key: 5, label: `履职机构类型`, visible: true },
        { key: 6, label: `履职角色`, visible: true },
        { key: 7, label: `履职周期`, visible: true },
        // { key: 8, label: `履职次数`, visible: true },
        { key: 8, label: `履职时间`, visible: true },
        { key: 9, label: `修改人`, visible: true },
        { key: 10, label: `计划状态`, visible: true },
      ],
    };
  },
  props: {},
  watch: {},
  computed: {
    ...mapGetters(["orgId", "orgName"]),
    orgTypeOptions(){
     if(!this.dict || !this.dict.type.sys_org_type==null)  {
      return []
     }
     
     return this.dict.type.sys_org_type.filter(t=>!["1","2","7","8"].includes(t.value))
    }
  },
  methods: {
    ...mapMutations([]),
    //判断是否跟当前用户同机构
    eqOrg(row) {
      // console.log(row.planOfOrgId,"row.planOfOrgId");
      // console.log(this.orgId,"this.orgId");
      if (
        row != null &&
        row != undefined &&
        (row.planCreateOrgId == this.orgId ||
          (row.planOfOrgType == 3 && row.planOfOrgId == this.orgId))
      ) {
        return true;
      }
      return false;
    },
    // eqOrg2(row) {
    //   // console.log(row.planCreateOrgId,"row.planCreateOrgId");
    //   // console.log(this.orgId,"this.orgId");
    //   if (
    //     row != null &&
    //     row != undefined &&
    //     row.planCreateOrgId == this.orgId &&
    //     row.planOfOrgId == this.orgId
    //   ) {
    //     return true;
    //   }
    //   return false;
    // },
    showPublish(row) {
      //有父计划且父计划不是使用中状态，不能下发
      if (row.parentStatus != 1 && row.parentId>0) {
        return false;
      }
      //可以下发:本机构创建+状态为草稿、停用的计划
      if (
        row.planCreateOrgId == this.orgId &&
        (row.planStatus == 0 || row.planStatus == 2)
      ) {
        return true;
      }

      // if (
      //   row.planOfOrgId == this.orgId &&
      //   row.planCreateOrgId != this.orgId &&
      //   (row.planStatus == 0 || row.planStatus == 2) &&
      //   row.distributePlanStatus == 0
      // ) {
      //   return true;
      // }

      return false;
    },
    showDelete(row) {
      //本机构创建的计划，才能删除
      return row.planCreateOrgId == this.orgId;
    },
    showWithDraw(row) {
      //本机构创建是自己+状态为使用中

      if (row.planCreateOrgId == this.orgId && row.planStatus == 1) {
        return true;
      }

      // if (
      //   row.planOfOrgId == this.orgId &&
      //   row.planCreateOrgId != this.orgId &&
      //   row.planStatus == 1 &&
      //   row.distributePlanStatus == 0
      // ) {
      //   return true;
      // }

      return false;
    },
    // //已完成下发的计划不显示下发按钮
    // checkCanPublish(row) {
    //   // console.log(row.planStatus,"row.planStatus")
    //   if (row.planOfOrgType == "1" && row.distribute == 0) {
    //     return true;
    //   }
    //   return false;
    // },
    // newcheckCanPublish(row) {
    //   //如果计划所属机构类型为行社并且计划不为进行中并且计划创建机构为当前机构或者
    //   //计划状态为停用并且不属于子计划并且计划所属机构类型为省联社
    //   if (
    //     (row.planOfOrgType == 3 &&
    //       row.planStatus != 1 &&
    //       row.planCreateOrgId == this.orgId) ||
    //     (row.planStatus == 2 && row.parentId != -1 && row.planOfOrgType == 1)
    //   ) {
    //     return true;
    //   }
    //   return false;
    // },
    //开始撤回
    chhuile(row) {
      let msg = "";
      if (row.taskHasCompleted != 1) {
        msg = "因不存在已完成任务，撤回后将删除所有生成任务?";
      } else {
        msg = "因存在已完成任务，撤回后下周期起将不再生成任务?";
      }
      this.$modal
        .confirm(msg, "提示")
        .then(() => {
          // 用户点击了确认按钮
          // console.log("执行操作...");
          this.loading = true;
          api.cheHui(row.id).then((response) => {
            this.getList();
            this.loading = false;
          });
        })
        .catch(() => {
          // 用户点击了取消按钮
          // console.log("取消操作...");
        });
    },
    //已下发的显示撤回
    // chehui(row) {
    //   if (row.distribute == 1 && row.planCreateOrgId == this.orgId) {
    //     return true;
    //   }
    //   return false;
    // },
    sel(selectList, row) {
      let msg = "";
      if (row.planStatus == 0) {
        msg = "请选择下发后立即生成或下周期生成任务。";
        this.$refs["DialogThreeState"].show(
          msg,
          (state) => {
            if (state == 0 || state == 1) {
              this.distributeInner(selectList, state == 1);
            }
          },
          {
            yesText: "立即生成",
            noText: "下周期",
            cancelText: "取消",
          }
        );
      } else if (row.planStatus == 2) {
        this.$modal
          .confirm("因存在已完成任务，是否确定从下周期生成任务？")
          .then(() => {
            this.distributeInner(selectList, false);
          });
      } else {
        this.distributeInner(selectList, false);
      }
    },
    distributeInner(selectList, imme) {
      this.loading = true;
      api
        .distribute(selectList, imme)
        .then((response) => {
          this.getList();
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },

    onHSPlanDistribute(row) {
      if (row.planStatus == 0) {
        let msg = "请选择下发后立即生成或下周期生成任务。";
        this.$refs["DialogThreeState"].show(
          msg,
          (state) => {
            if (state == 0 || state == 1) {
              this.distributeHS(row.id, state == 1);
            }
          },
          {
            yesText: "立即生成",
            noText: "下周期",
            cancelText: "取消",
          }
        );
      } else if (row.planStatus == 2) {
        this.$modal
          .confirm("因存在已完成任务，是否确定从下周期生成任务？")
          .then(() => {
            this.distributeHS(row.id, false);
          });
      } else {
        this.distributeHS(row.id, false);
      }
    },
    distributeHS(id, immediateEffect) {
      this.loading = true;
      api
        .distributeHS(id, immediateEffect)
        .then((response) => {
          // console.log(response, "then");
          if (response.data == 0) {
            this.loading = false;
          } else {
            this.getList();
            this.loading = false;
          }
        })
        .catch((response) => {
          // console.log(response, "catch");
          this.getList();
          this.loading = false;
        });
    },
    showDialogDistribute(row) {
      if (row.planOfOrgType == 3) {
        this.onHSPlanDistribute(row);
      } else {
        this.$refs.dialogDistribute.show(row);
      }
      // this.loading = true;
      // api
      //   .distributeCheHui(row.id)
      //   .then((response) => {
      //     // console.log(response, "then");
      //     if (response.data == 0) {
      //       this.loading = false;
      //       this.$refs.dialogDistribute.show(row);
      //     } else {
      //       this.getList();
      //       this.loading = false;
      //     }
      //   })
      //   .catch((response) => {
      //     // console.log(response, "catch");
      //     this.getList();
      //     this.loading = false;
      //     this.$refs.dialogDistribute.show(row);
      //   });
    },
    async getRolesByOrg() {
      await allRole().then((res) => {
        // console.info(res);
        this.resumptionRoles = res.data;
      });
    },
    getList() {
      this.loading = true;
      this.queryParams.roleList = [];
      if (
        this.queryParams.resumptionRole != null &&
        this.queryParams.resumptionRole != ""
      ) {
        this.queryParams.roleList.push(this.queryParams.resumptionRole);
      }

      console.info(this.dict.type);
      api
        .list(this.queryParams)
        .then((response) => {
          this.pageData = response.rows;
          this.total = response.total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    getDefaultKey(key) {
      this.queryParams.orgId = key;
      this.getList();
    },
    handleAdd(id, other = {}) {
      this.$refs.editDialog.show(id, other);
    },
    onEdit(id, other = {}) {
      this.$refs.editDialog.show(id, other);
    },
    async onDel(row) {
      let msg = "";
      if (row.planStatus == 0) {
        msg = '是否确认删除名称为"' + row.planName + '"的任务？';
      } else if (row.planStatus == 1) {
        if (row.planCycle == 1) {
          msg = "本次删除将强制删除今日所有任务?";
        } else {
          msg = "本次删除将强制删除当前任务时间及以后所有任务";
        }
      } else if (row.planStatus == 2) {
        if (row.hasTaskCurrentCycle) {
          if (row.planCycle == 1) {
            msg = "本次删除将强制删除今日所有任务?";
          } else {
            msg = "本次删除将强制删除当前任务时间及以后所有任务";
          }
        } else {
          msg = '是否确认删除名称为"' + row.planName + '"的任务？';
        }
      }
      this.$modal
        .confirm(msg)
        .then(() => {
          // 用户点击了确认按钮
          console.log("执行操作...");
          this.loading = true;
          api
            .del(row.id)
            .then(() => {
              this.getList();
              this.loading = false;
              this.$modal.msgSuccess("删除成功");
            })
            .catch(() => {
              this.loading = false;
            });
        })
        .catch(() => {
          // 用户点击了取消按钮
          console.log("取消操作...");
          this.loading = false;
        });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("search");
      this.queryParams.orgId = this.orgId;
      this.queryParams.checkSub = false;
      this.$refs["orgTree"].setCheckSub(this.queryParams.checkSub);
      // this.$refs.tree.setCurrentKey(null);
      this.getList();
    },
    //单选框状态改变
    checkChange(state) {
      this.queryParams.checkSub = state;
      this.getList();
    },
    // 节点单击事件
    clickTreeNode(data) {
      this.queryParams.orgId = data.id;
      this.getList();
    },
    getStatusLabel(value) {
      return getLabel(statusOptions, value);
    },
    getLabel(options, value) {
      return getLabel(options, value);
    },
    //apimark//
  },
  mounted() {},
};
</script>

<style lang="scss" scoped>
.brand {
}
</style>
