<template>
  <div class="process-designer-container">
    <apass-list
      ref="list"
      search-placeholder="请输入关键字"
      :list-filter="filterList"
      :list-header="listHeader"
      :list-data="listData"
      :list-total="listTotal"
      @list-action="init"
      :list-padding-left="40"
    >
      <el-button type="primary" slot="header-left" @click="addNewProcess">
        新建流程
      </el-button>

      <el-breadcrumb separator="/" slot="breadcrumb">
        <el-breadcrumb-item>
          在线组件工具
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          流程设计
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          流程管理
        </el-breadcrumb-item>
      </el-breadcrumb>
    </apass-list>

    <apass-dialog
      ref="dialog"
      :title="dialogInfo.title"
      :msg="dialogInfo.msg"
      :cancel-text="dialogInfo.cancelText"
      :submit="dialogInfo.submit"
      :sunbmit-text="dialogInfo.sunbmitText"
    ></apass-dialog>

    <apass-dialog ref="copyProcess" title="复制流程">
      <template slot="content">
        <el-form
          v-if="copyTempItem"
          ref="detail_form"
          class="apaas_detail_form"
          label-position="top"
          :model="copyTempItem"
          :rules="copyTempItem_rules"
        >
          <el-form-item label="流程名称：" prop="newName">
            <el-input
              v-model="copyTempItem.newName"
              placeholder="请输入流程名称"
            ></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template slot="action">
        <el-button type="defalut" size="mini" @click="cancelCopyProcess">
          取消
        </el-button>
        <el-button type="primary" size="mini" @click="submitCopyProcess">
          保存
        </el-button>
      </template>
    </apass-dialog>
  </div>
</template>

<script>
import helper from "@/services/helper.js";
import apassList from "@/components/apass-list";
import apassDialog from "@/components/apass-dialog";

export default {
  components: {
    apassList,
    apassDialog,
  },
  data: () => ({
    filterList: [
      {
        name: "服务领域",
        prop: "service_domains",
        data: [],
      },
      {
        name: "工作区域",
        prop: "workareas",
        data: [],
      },
      {
        name: "流程状态",
        prop: "states",
        data: [],
      },
    ],
    listHeader: [],
    listData: [],
    listTotal: 0,
    dialogInfo: {
      title: "",
      msg: "",
      cancelText: "",
      submit: null,
      sunbmitText: "",
    },
    tempFilter: null,
    copyTempItem: null,
    copyTempItem_rules: {
      newName: [
        { required: true, message: "请输入流程名称", trigger: "blur" },
        { max: 16, message: "不能超过16个字符", trigger: "blur" },
      ],
    },
  }),
  methods: {
    init(filter) {
      let params = {
        sectors:
          (filter.service_domains &&
            filter.service_domains.map((item) => item.value).join(",")) ||
          "",
        workareas:
          (filter.workareas &&
            filter.workareas.map((item) => item.value).join(",")) ||
          "",
        states:
          (filter.states &&
            filter.states.map((item) => item.value).join(",")) ||
          "",
        filter_by: filter.keyword,
        page: filter.page,
        page_size: filter.size,
      };

      this.tempFilter = filter;

      this.$http
        .get("/apaas/serviceapp/v3/workflows/list", { params })
        .then(({ data }) => {
          if (data.success === 1) {
            this.listTotal = data.total;
            this.listData = data.data;
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    initFilter() {
      this.$http
        .get("/apaas/serviceapp/v3/workflows/searchConditions")
        .then(({ data }) => {
          if (data.success === 1) {
            let datas = data.data;
            this.filterList.forEach((item) => {
              let filter = datas[item.prop] || [];

              this.$set(
                item,
                "data",
                filter.map((item) => ({
                  name: item.name,
                  value: item.id,
                }))
              );
            });
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    iniHeader() {
      this.listHeader = [
        {
          label: "流程编号",
          prop: "workflows_code",
          width: 180,
        },
        {
          label: "流程名称",
          prop: "name",
          type: "button",
          callback: this.detailItem,
        },
        {
          label: "服务领域",
          prop: "sector_name",
          align: "center",
          width: 240,
        },
        {
          label: "创建时间",
          prop: "create_time",
          getText(item) {
            return helper.dateStringTransform(item.create_time || "");
          },
          align: "center",
          width: 180,
        },
        {
          label: "状态",
          prop: "state",
          getText(item) {
            return ["未部署", "已部署", "已发布"][item.state || 0];
          },
          align: "center",
          width: 180,
        },
        {
          label: "工作区域",
          prop: "workarea_name",
          align: "center",
          width: 180,
        },
        {
          label: "操作",
          type: "buttons",
          align: "center",
          width: 300,
          actionList: [
            {
              label: "发布",
              callback: this.publishItem,
              disableHide: true,
              disabledRule(item) {
                return item.state == 2;
              },
            },
            {
              label: "编辑",
              callback: this.editItem,
            },
          ],
          moreActionList: [
            {
              label: "取消发布",
              callback: this.cancelPublishItem,
              showRule(item) {
                return item.state === 2;
              },
            },
            {
              label: "部署",
              callback: this.deployItem,
              showRule(item) {
                return item.state === 0;
              },
            },
            {
              label: "取消部署",
              callback: this.cancelDeployItem,
              showRule(item) {
                return item.state === 1;
              },
            },
            {
              label: "复制",
              callback: this.copyItem,
              showRule(item) {
                return true;
              },
            },
            {
              label: "删除",
              callback: this.deleteItem,
              showRule(item) {
                return item.state !== 2;
              },
            },
          ],
        },
      ];
    },
    refreshPage() {
      this.init(this.tempFilter);
    },
    showDialog() {
      this.$refs.dialog.show();
    },
    copyProcessShow() {
      this.$refs.copyProcess.show();
    },
    copyProcessHide() {
      this.$refs.copyProcess.hide();
      this.copyTempItem = null;
    },
    addNewProcess() {
      this.$router.push("/progress/designer/design");
    },
    editItem(item) {
      this.$router.push(`/progress/designer/design_edit/${item.workflows_id}`);
    },
    detailItem(item) {
      this.$router.push(`/progress/designer/detail/${item.workflows_id}`);
    },
    publishItem(item) {
      this.dialogInfo.title = "提示";
      this.dialogInfo.msg = `发布后流程后，流程将部署到工作区域并上架到服务超市，是否发布该流程？`;
      this.dialogInfo.cancelText = "取消";
      this.dialogInfo.sunbmitText = "发布";
      this.dialogInfo.submit = () => {
        this.$router.push(`/fwzc/fwcs?process=${item.workflows_id}`);
      };
      this.showDialog();
    },
    cancelPublishItem(item) {
      this.dialogInfo.title = "提示";
      this.dialogInfo.msg = `取消发布后，该流程服务将从服务超市下架，仅部署在工作区域${item.workarea_name}中，是否取消发布流程服务“${item.name}”？`;
      this.dialogInfo.cancelText = "暂不";
      this.dialogInfo.sunbmitText = "取消发布";
      this.dialogInfo.submit = () => {
        this.$http
          .delete("/apaas/serviceapp/v3/workflows/cancelPublish", {
            params: {
              id: item.workflows_id,
            },
          })
          .then(({ data }) => {
            if (data.success === 1) {
              this.$message.success(data.errMsg || "取消发布成功");
              this.refreshPage();
            } else {
              this.$message.error(data.errMsg || "取消发布失败");
            }
          })
          .catch((error) => {
            console.log(error);
            this.$message.error("取消发布失败");
          });
      };
      this.showDialog();
    },
    deployItem(item) {
      this.dialogInfo.title = "提示";
      this.dialogInfo.msg = `部署流程后，流程将部署到工作区域，但不会上架到服务超市，是否部署该流程？`;
      this.dialogInfo.cancelText = "取消";
      this.dialogInfo.sunbmitText = "部署";
      this.dialogInfo.submit = () => {
        let form = new FormData();
        form.append("id", item.workflows_id);

        this.$http
          .post("/apaas/serviceapp/v3/workflows/deploy", form)
          .then(({ data }) => {
            if (data.success === 1) {
              this.$message.success(data.errMsg || "部署成功");
              this.refreshPage();
            } else {
              this.$message.error(data.errMsg || "部署失败");
            }
          })
          .catch((error) => {
            console.log(error);
            this.$message.error("部署失败");
          });
      };
      this.showDialog();
    },
    cancelDeployItem(item) {
      this.dialogInfo.title = "提示";
      this.dialogInfo.msg = `取消部署后，该流程服务不能通过链接访问，是否取消部署流程服务“${item.name}”？`;
      this.dialogInfo.cancelText = "取消";
      this.dialogInfo.sunbmitText = "取消部署";
      this.dialogInfo.submit = () => {
        this.$http
          .delete("/apaas/serviceapp/v3/workflows/cancelDeploy", {
            params: {
              id: item.workflows_id,
            },
          })
          .then(({ data }) => {
            if (data.success === 1) {
              this.$message.success(data.errMsg || "取消部署成功");
              this.refreshPage();
            } else {
              this.$message.error(data.errMsg || "取消部署失败");
            }
          })
          .catch((error) => {
            console.log(error);
            this.$message.error("取消部署失败");
          });
      };
      this.showDialog();
    },
    copyItem(item) {
      this.copyTempItem = {
        ...item,
        newName: "",
      };
      this.copyProcessShow();
    },
    cancelCopyProcess() {
      this.copyProcessHide();
    },
    submitCopyProcess() {
      this.$refs.detail_form.validate((valid) => {
        if (valid) {
          let form = new FormData();
          form.append("id", this.copyTempItem.workflows_id);
          form.append("name", this.copyTempItem.newName);

          this.$http
            .post("/apaas/serviceapp/v3/workflows/copy", form)
            .then(({ data }) => {
              if (data.success === 1) {
                this.$message.success(data.errMsg || "复制成功");
                this.copyProcessHide();
                this.refreshPage();
              } else {
                this.$message.error(data.errMsg || "复制失败");
              }
            })
            .catch((error) => {
              console.log(error);
              this.$message.error("复制失败");
            });
        } else {
          return false;
        }
      });
    },
    deleteItem(item) {
      this.dialogInfo.title = "提示";
      this.dialogInfo.msg = `您确定要删除流程服务“${item.name}”吗？`;
      this.dialogInfo.cancelText = "取消";
      this.dialogInfo.sunbmitText = "确定";
      this.dialogInfo.submit = () => {
        this.$http
          .delete("/apaas/serviceapp/v3/workflows/del", {
            params: {
              id: item.workflows_id,
            },
          })
          .then(({ data }) => {
            if (data.success === 1) {
              this.$message.success(data.errMsg || "删除成功");
              this.refreshPage();
            } else {
              this.$message.error(data.errMsg || "删除失败");
            }
          })
          .catch((error) => {
            console.log(error);
            this.$message.error("删除失败");
          });
      };
      this.showDialog();
    },
  },
  created() {
    this.initFilter();
    this.iniHeader();
  },
};
</script>

<style scoped>
.process-designer-container {
  height: 100%;
}
.apaas_detail_form {
  text-align: left;
  margin-top: 20px;
}
.apaas_detail_form .el-form-item {
  margin: 0;
}
</style>
