<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="工作流名称" prop="workflowName">
        <el-input
          v-model="queryParams.workflowName"
          placeholder="请输入工作流名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工作流类型" prop="workflowType">
        <el-select v-model="queryParams.workflowType" placeholder="请选择类型" clearable size="small">
          <el-option
            v-for="dict in workflowTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </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 statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </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"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" border :data="workflowList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="workflowId" width="80" />
      <el-table-column label="工作流名称" align="center" prop="workflowName" min-width="150" show-overflow-tooltip />
      <el-table-column label="描述" align="center" prop="workflowDesc" min-width="200" show-overflow-tooltip />
      <el-table-column label="类型" align="center" prop="workflowType" width="100">
        <template slot-scope="scope">
          <dict-tag :options="workflowTypeOptions" :value="scope.row.workflowType"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createByName"/>
      <el-table-column label="创建部门" align="center" prop="createByDeptName"/>
      <el-table-column label="版本" align="center" prop="version" width="60" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
          >设计</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-user"
            @click="handleBindSales(scope.row)"
          >绑定销售</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document-copy"
            @click="handleCopy(scope.row)"
          >复制</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleVersion(scope.row)"
          >历史版本</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"
    />

    <!-- 绑定销售弹窗 -->
    <el-dialog title="绑定销售" :visible.sync="bindSalesOpen" width="500px" append-to-body>
      <!-- 当前绑定的销售 -->
      <div class="current-sales">
        <div class="section-title">当前绑定销售</div>
        <div v-if="currentBindUserList && currentBindUserList.length > 0" class="bind-info">
          <el-tag
            v-for="(user, index) in currentBindUserList"
            :key="index"
            type="success"
            style="margin-right: 8px; margin-bottom: 8px;"
          >
            {{ user.userName || user.user_name }}（{{ user.nickName || user.nick_name }}）
          </el-tag>
        </div>
        <div v-else class="no-bind">
          <el-tag type="info">暂未绑定销售</el-tag>
        </div>
      </div>

      <!-- 可选销售列表 -->
      <div class="sales-list">
        <div class="section-title">选择销售</div>
        <el-input
          v-model="salesSearchKey"
          placeholder="搜索昵称"
          size="small"
          prefix-icon="el-icon-search"
          clearable
          style="margin-bottom: 10px"
        />
        <el-table
          :data="filteredCompanyUserList"
          v-loading="salesLoading"
          border
          height="300"
          :row-key="getSalesRowKey"
          :row-class-name="salesRowClassName"
          @selection-change="handleSalesSelectionChange"
          ref="salesTable"
        >
          <el-table-column type="selection" width="55" align="center" :selectable="checkSelectable" :reserve-selection="true" />
          <el-table-column label="用户名" align="center" prop="userName" />
          <el-table-column label="昵称" align="center" prop="nickName" />
        </el-table>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleBindSalesCancel">取 消</el-button>
        <el-button type="primary" :disabled="selectedSalesList.length === 0" @click="confirmBindSales">确 定</el-button>
      </div>
    </el-dialog>


    <!-- 历史版本弹窗 -->
    <el-dialog
      title="历史版本"
      :visible.sync="versionOpen"
      width="60%"
      custom-class="version-dialog"
      append-to-body
    >
      <el-table
          v-loading="versionLoading"
          :data="versionList"
          border
          size="small"
      >
          <el-table-column label="版本号" align="center" width="120">
              <template slot-scope="scope">
                  <el-tag v-if="scope.row.versionNo === currentVersionNo" type="warning">
                      v{{ scope.row.versionNo }}（当前）
                  </el-tag>
                  <el-tag v-else type="success">
                      v{{ scope.row.versionNo }}
                  </el-tag>
              </template>
          </el-table-column>

          <el-table-column label="工作流名称" align="center" prop="workflowName" min-width="60" />

          <el-table-column label="快照时间" align="center" width="170">
              <template slot-scope="scope">
                  <span>{{scope.row.snapshotTime }}</span>
              </template>
          </el-table-column>

          <el-table-column label="操作人" align="center" prop="snapshotBy" width="120" />

          <el-table-column label="操作" align="center" width="180">
              <template slot-scope="scope">
                  <el-button
                      type="text"
                      size="mini"
                      @click="handleViewVersion(scope.row)"
                  >查看</el-button>
                  <el-button
                      v-if="versionList.length > 1 && scope.row.versionNo !== currentVersionNo"
                      type="text"
                      size="mini"
                      style="color: #f56c6c"
                      @click="handleRollbackVersion(scope.row)"
                  >回退</el-button>
              </template>
          </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
          <el-button @click="versionOpen = false">关闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { myListWorkflow, delWorkflow, updateWorkflowStatus, copyWorkflow, exportWorkflow, getBindCompanyUserByWorkflowId,
         listCompanyUser, updateWorkflowBindCompanyUser, getWorkflowVersionList, getWorkflowVersionDetail, rollbackWorkflowVersion} from '@/api/company/companyWorkflow'

export default {
  name: 'myCompanyWorkflow',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工作流表格数据
      workflowList: [],
      // 工作流类型字典
      workflowTypeOptions: [
        { dictValue: '1', dictLabel: '对话流程' },
        { dictValue: '2', dictLabel: '任务流程' },
        { dictValue: '3', dictLabel: '审批流程' }
      ],
      // 状态字典
      statusOptions: [
        { dictValue: '1', dictLabel: '启用' },
        { dictValue: '0', dictLabel: '禁用' }
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        workflowName: null,
        workflowType: null,
        status: null
      },
      // 绑定销售弹窗
      bindSalesOpen: false,
      // 销售列表加载
      salesLoading: false,
      // 当前操作的工作流
      currentWorkflow: null,
      // 当前绑定的用户列表
      currentBindUserList: [],
      // 销售列表
      companyUserList: [],
      // 选中的销售列表
      selectedSalesList: [],
      // 销售搜索关键字
      salesSearchKey: '',
      // 历史版本弹窗
      versionOpen: false,
      // 版本列表
      versionList: [],
      // 加载状态
      versionLoading: false,
      // 当前版本详情弹窗
      versionDetailOpen: false,
      // 当前版本详情加载
      versionDetailLoading: false,
      // 当前版本详情
      versionDetail: {
        workflowVersion: {},
        nodes: [],
        edges: []
      },
      currentVersionNo: null,
    }
  },
  computed: {
    // 过滤后的销售列表
    filteredCompanyUserList() {
      if (!this.salesSearchKey) {
        return this.companyUserList
      }
      const key = this.salesSearchKey.toLowerCase()
      return this.companyUserList.filter(item => {
        return (item.nickName && item.nickName.toLowerCase().includes(key))
      })
    }
  },
  created() {
    this.getList()
    // 如果有字典配置，可以使用以下方式获取
    // this.getDicts("ai_workflow_type").then(response => {
    //   this.workflowTypeOptions = response.data
    // })
  },
  watch: {
    '$route.query.openVersionWorkflowId': {
        handler(val) {
            if (val) {
                this.$nextTick(() => {
                    this.autoOpenVersionDialog(val)
                })
            }
        },
        immediate: true
    }
  },
  methods: {
    /** 查询工作流列表 */
    getList() {
        this.loading = true
        myListWorkflow(this.queryParams).then(response => {
            this.workflowList = response.rows
            this.total = response.total
            this.loading = false

            const workflowId = this.$route.query.openVersionWorkflowId
            if (workflowId) {
                this.$nextTick(() => {
                    this.autoOpenVersionDialog(workflowId)
                })
            }
        }).catch(() => {
            this.loading = false
        })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.workflowId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push('/companyWx/companyWorkflow/design')
    },
    /** 设计按钮操作 */
    handleEdit(row) {
      this.$router.push('/companyWx/companyWorkflow/design/' + row.workflowId)
    },
    /** 复制按钮操作 */
    handleCopy(row) {
      this.$confirm('是否确认复制该工作流?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return copyWorkflow(row.workflowId)
      }).then(() => {
        this.getList()
        this.msgSuccess('复制成功')
      }).catch(() => {})
    },
    /** 状态修改 */
    handleStatusChange(row) {
      const text = row.status === 1 ? '启用' : '停用'
      this.$confirm('确认要"' + text + '"该工作流吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return updateWorkflowStatus(row.workflowId, row.status)
      }).then(() => {
        this.msgSuccess(text + '成功')
      }).catch(() => {
        row.status = row.status === 1 ? 0 : 1
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const workflowIds = row.workflowId || this.ids
      this.$confirm('是否确认删除工作流编号为"' + workflowIds + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return delWorkflow(workflowIds)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有工作流数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.exportLoading = true
        return exportWorkflow(queryParams)
      }).then(response => {
        this.download(response.msg)
        this.exportLoading = false
      }).catch(() => {})
    },
    /** 绑定销售按钮操作 */
    handleBindSales(row) {
      this.currentWorkflow = row
      this.currentBindUserList = []
      this.selectedSalesList = []
      this.salesSearchKey = ''
      this.bindSalesOpen = true
      this.salesLoading = true
      console.log(11111)
      // 获取当前绑定的销售列表
      getBindCompanyUserByWorkflowId(row.workflowId).then(res => {
        this.currentBindUserList = res.data.data || []
      }).catch(() => {})
      console.log(this.currentBindUserList)
      // 获取销售列表
      listCompanyUser().then(res => {
        this.companyUserList = res.data || res.rows || []
        this.salesLoading = false
      }).catch(() => {
        this.salesLoading = false
      })
    },
    /** 销售勾选变化 */
    handleSalesSelectionChange(selection) {
      this.selectedSalesList = selection
    },
    /** 获取销售行key */
    getSalesRowKey(row) {
      return row.userId || row.companyUserId || row.id
    },
    /** 取消绑定销售弹窗 */
    handleBindSalesCancel() {
      this.bindSalesOpen = false
      this.selectedSalesList = []
      this.$refs.salesTable && this.$refs.salesTable.clearSelection()
    },
    /** 销售行样式 */
    salesRowClassName({ row }) {
      if (this.isCurrentBindUser(row)) {
        return 'disabled-row'
      }
      return ''
    },
    /** 判断是否为当前绑定用户 */
    isCurrentBindUser(row) {
      if (!this.currentBindUserList || this.currentBindUserList.length === 0) {
        return false
      }
      const rowUserId = row.userId || row.companyUserId || row.user_id
      return this.currentBindUserList.some(user => {
        const bindUserId = user.userId || user.companyUserId || user.user_id
        return bindUserId == rowUserId
      })
    },
    /** 检查是否可选 */
    checkSelectable(row) {
      return !this.isCurrentBindUser(row)
    },
    /** 确认绑定销售 */
    confirmBindSales() {
      if (this.selectedSalesList.length === 0) {
        this.msgWarning('请选择要绑定的销售')
        return
      }

      const workflowId = this.currentWorkflow.workflowId
      const companyUserIds = this.selectedSalesList.map(item => item.userId || item.companyUserId)

      this.doBindSales(workflowId, companyUserIds)
    },
    /** 执行绑定销售 */
    doBindSales(workflowId, companyUserIds) {
      updateWorkflowBindCompanyUser({
        workflowId: workflowId,
        companyUserIds: companyUserIds
      }).then(() => {
        this.msgSuccess('绑定成功')
        this.bindSalesOpen = false
        this.getList()
      })
    },
    /** 打开历史版本弹窗 */
    handleVersion(row) {
      this.currentWorkflow = row
      this.currentVersionNo = row.version
      this.versionOpen = true
      this.versionLoading = true
      this.versionList = []

      getWorkflowVersionList(row.workflowId).then(res => {
          this.versionList = res.data || []
          this.versionLoading = false
      }).catch(() => {
          this.versionLoading = false
      })
    },

    /** 查看版本详情 */
    handleViewVersion(row) {
        this.$router.push({
            path: '/companyWorkflow/version-preview/' + row.versionId,
            query: {
                workflowId: this.currentWorkflow.workflowId
            }
        })
    },

    /** 一键回退 */
    handleRollbackVersion(row) {
      this.$confirm('是否确认回退到版本 v' + row.versionNo + ' ?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
      }).then(() => {
          return rollbackWorkflowVersion(row.versionId)
      }).then(() => {
          this.msgSuccess('回退成功')
          this.versionOpen = false
          this.versionDetailOpen = false
          this.getList()
      }).catch(() => {})
    },
    /** 自动打开历史版本弹窗 */
    autoOpenVersionDialog(workflowId) {
      const row = this.workflowList.find(item => String(item.workflowId) === String(workflowId))
      if (!row) {
          return
      }
      this.handleVersion(row)

      // 清掉 query，避免重复触发
      const query = { ...this.$route.query }
      delete query.openVersionWorkflowId
      this.$router.replace({
          path: this.$route.path,
          query
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.current-sales {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;

  .section-title {
    font-weight: 600;
    margin-bottom: 10px;
    color: #333;
  }

  .bind-info {
    .el-tag {
      font-size: 14px;
      padding: 8px 15px;
      height: auto;
      line-height: 1.5;
      white-space: normal;
    }
  }

  .no-bind {
    .el-tag {
      font-size: 14px;
      padding: 8px 15px;
      height: auto;
    }
  }
}

.sales-list {
  .section-title {
    font-weight: 600;
    margin-bottom: 10px;
    color: #333;
  }
}
</style>

<style lang="scss">
.el-table .disabled-row {
  background-color: #f5f5f5;
  color: #999;

  &:hover > td {
    background-color: #f5f5f5 !important;
  }
}
</style>
