<template>
  <div class="app-container">
    <el-form
      ref="elForm"
      :model="formData"
      :rules="rules"
      size="medium"
      label-width="100px"
      :label-position="labelPosition"
    >
      <h2 style="color: #409eff; background: #e8e8e8; padding: 15px; border-radius: 10px">基本信息</h2>
      <div style="padding: 0 0 0 10px">
        <el-row>
          <el-col :span="6">
            <el-form-item label-width="120px" label="审批流名称" prop="examineName">
              <el-input
                v-model="formData.examineName"
                placeholder="请输入审批流名称"
                :maxlength="60"
                show-word-limit
                clearable
                v-no-whitespace
                :style="{ width: '86.5%' }"
                @blur="checkIsExistFlowName"
                :disabled="edit || paramsData.type === 'view'"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label-width="120px" label="审批流编号" prop="definitionKey">
              <el-input
                v-model="formData.definitionKey"
                placeholder="自动生成"
                :maxlength="60"
                show-word-limit
                clearable
                v-no-whitespace
                :style="{ width: '86.5%' }"
                :disabled="true || paramsData.type === 'view'"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label-width="120px" label="审批流类型" prop="examineType">
              <el-select
                v-model="formData.examineType"
                placeholder="请选择审批流"
                clearable
                :style="{ width: '86.5%' }"
                @change="change"
                @clear="clearPro"
                :disabled="edit || paramsData.type === 'view'"
              >
                <el-option label="专用审批流" value="1" />
                <el-option label="通用审批流" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="适用范围" prop="resource">
              <el-radio-group v-model="formData.resource" disabled>
                <el-radio :label="1">全部</el-radio>
                <el-radio :label="2">部分工程</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="工程"
              prop="proId"
              v-if="formData.examineType === '1' || formData.examineType === '专用审批流'"
            >
              <el-select
                v-model="formData.proId"
                placeholder="请选择工程"
                clearable
                style="width: 86.5%"
                @change="changeType"
                @clear="clearBusiness"
                :disabled="edit || paramsData.type === 'view'"
              >
                <el-option v-for="item in proOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label-width="120px" label="审批业务类型" prop="businessType">
              <el-select
                v-model="formData.businessType"
                placeholder="请选择审批业务类型"
                clearable
                :style="{ width: '86.5%' }"
                :disabled="edit || paramsData.type === 'view'"
              >
                <el-option v-for="item in flowOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18">
            <el-form-item label="审批流说明" prop="examineMark">
              <el-input
                type="textarea"
                v-model="formData.examineMark"
                maxlength="200"
                :disabled="paramsData.type === 'view'"
                v-no-whitespace
                show-word-limit
                :style="{ width: '96%' }"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <h2 style="color: #409eff; background: #e8e8e8; padding: 15px; border-radius: 10px">审批流程设置</h2>
      <el-container>
        <el-main>
          <el-row v-for="(item, index) in formData.processSetupItems" :key="index">
            <div style="padding: 0 0 30px 10px">
              <el-row>
                <el-button type="primary" @click="addAddressOption" v-if="paramsData.type !== 'view'">
                  添加节点
                </el-button>
                <el-button
                  type="danger"
                  v-if="index !== 0 && paramsData.type !== 'view'"
                  @click="removeLastItem(index)"
                >
                  删除节点
                </el-button>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item
                    :label="'审批节点 ' + (index + 1)"
                    :prop="'processSetupItems.' + index + '.nodeName'"
                    :rules="{ required: true, message: '请选择审批节点', trigger: 'blur' }"
                  >
                    <el-input
                      v-model="item.nodeName"
                      placeholder="请输入审批节点"
                      :maxlength="60"
                      show-word-limit
                      clearable
                      v-no-whitespace
                      :disabled="paramsData.type === 'view'"
                      :style="{ width: '86.5%' }"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item
                    label="审批部门"
                    :prop="'processSetupItems.' + index + '.deptId'"
                    :rules="{ required: true, message: '请选择审批部门', trigger: 'blur' }"
                  >
                    <Treeselect
                      v-model="item.deptId"
                      :options="deptOptions"
                      :show-count="true"
                      placeholder="请选择归属部门"
                      :style="{ width: '86.5%' }"
                      class="treeselectMain"
                      :disabled="paramsData.type === 'view'"
                      :noResultsText="'未找到相关部门！'"
                      @select="UserType"
                      :append-to-body="true"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item
                    label="选择成员"
                    :prop="'processSetupItems.' + index + '.checkPerson'"
                    :rules="{ required: true, message: '请选择选择成员', trigger: 'blur' }"
                  >
                    <el-select
                      v-model="item.checkPerson"
                      placeholder="请选择选择成员"
                      multiple
                      filterable
                      :disabled="item.deptId === undefined || paramsData.type === 'view'"
                      @change="changeUser($event, index)"
                      :style="{ width: '86.5%' }"
                    >
                      <el-option
                        v-for="dict in userOptions"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="16">
                  <el-form-item
                    label="审批方式"
                    :prop="'processSetupItems.' + index + '.examineTypes'"
                    :rules="{ required: true, message: '请选择审批方式', trigger: 'blur' }"
                  >
                    <el-radio-group
                      v-model="item.examineTypes"
                      style="display: flex; flex-direction: column"
                      :disabled="paramsData.type === 'view'"
                    >
                      <el-radio :label="'0'" :value="0" style="margin-bottom: 20px">
                        依次审批（按先后顺序，一人审批完成后流转到下一人）
                      </el-radio>
                      <el-radio :label="'1'" :value="1" style="margin-bottom: 20px">会签审批（需所有人同意）</el-radio>
                      <el-radio :label="'2'" :value="2" style="margin-bottom: 20px">或签审批（一人同意即可）</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="抄送人员" v-if="index === formData.processSetupItems.length - 1">
                    <!--                    :prop="'ccPerson'"-->
                    <!--                    :rules="{required: true, message: '请选择抄送成员', trigger: 'blur'}"-->
                    <el-select
                      v-model="formData.ccPerson"
                      placeholder="请选择选择成员"
                      clearable
                      multiple
                      filterable
                      :disabled="paramsData.type === 'view'"
                      :style="{ width: '86.5%' }"
                    >
                      <el-option
                        v-for="dict in ccPersonOptions"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item
                    label="是否支持终审"
                    v-if="index !== formData.processSetupItems.length - 1"
                    :prop="'processSetupItems.' + index + '.finalJudgment'"
                    :rules="{ required: true, message: '请选择是否支持终审', trigger: 'blur' }"
                  >
                    <el-select
                      v-model="item.finalJudgment"
                      placeholder="请选择是否支持终审"
                      :style="{ width: '86.5%' }"
                      :disabled="paramsData.type === 'view'"
                    >
                      <el-option label="是" value="1" />
                      <el-option label="否" value="0" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-row>
          <el-footer>
            <el-button type="primary" @click="submitConsForm" v-if="paramsData.type !== 'view'" v-preventReClick="5000">
              保 存
            </el-button>
          </el-footer>
        </el-main>
        <el-aside width="25%" style="background: transparent; margin-top: 2%">
          <div style="display: flex; flex-direction: column; align-items: center">
            <div
              style="
                border-radius: 10px;
                padding: 15px;
                border: 1.5px solid black;
                width: 50%;
                text-align: center;
                font-weight: bold;
              "
            >
              开始
            </div>
            <div class="arrow-container">
              <div class="line"></div>
              <div class="arrow-down"></div>
            </div>

            <div
              v-for="(item, index) in formData.processSetupItems"
              :key="index"
              style="width: 100%; display: flex; flex-direction: column; align-items: center"
            >
              <div
                style="
                  padding: 8px;
                  border: 1px solid black;
                  width: 50%;
                  text-align: center;
                  height: 50px;
                  font-size: 14px;
                  margin-top: 2px;
                "
              >
                {{ item.nodeName.length > 7 ? item.nodeName.substring(0, 7) + '...' : item.nodeName }}
              </div>
              <div class="arrow-container">
                <div class="line"></div>
                <div class="arrow-down"></div>
              </div>
            </div>
            <div
              style="
                border-radius: 10px;
                padding: 15px;
                border: 1.5px solid black;
                width: 50%;
                text-align: center;
                font-weight: bold;
              "
            >
              结束
            </div>
          </div>
        </el-aside>
      </el-container>
    </el-form>
  </div>
</template>
<script>
import { getProName, personnelDropDownBox, queryTheApprovalServiceType } from '@/api/tool/select'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { deptTreeSelect } from '@/api/system/user'
import { addExamine, checkIsExistFlowName, getExamine, updateExamine } from '@/api/flow/definition'
import { decryptCBC } from '@/utils/aescbc'
import { preparationPost } from '@/api/pro/proList'

export default {
  components: { Treeselect },
  name: 'auditProcess',
  data() {
    return {
      // 遮罩层
      loading: false,
      edit: false,
      formData: {
        proId: '',
        businessType: '',
        flowType: '',
        flowBusinessType: '',
        resource: '',
        ccPerson: '',
        ccPersons: '',
        //审批流程设置
        processSetupItems: [
          {
            nodeName: '',
            deptId: undefined,
            checkPerson: [],
            examineTypes: '',
            finalJudgment: '0',
          },
        ],
      },
      // 部门树选项
      deptOptions: undefined,
      flowOptions: [],
      proOptions: [],
      userOptions: [],
      ccPersonOptions: [],
      rules: {
        examineName: [{ required: true, message: '请输入审批流名称', trigger: 'blur' }],
        examineType: [{ required: true, message: '请选择审批流类型', trigger: 'change' }],
        businessType: [{ required: true, message: '请选择审批业务类型', trigger: 'change' }],
        proId: [{ required: true, message: '请选择工程', trigger: 'change' }],
        // ccPerson: [
        //   {required: true, message: '请选择抄送人员', trigger: 'change'}
        // ]
      },
      labelPosition: 'top',
      paramsData: {},
      isChangingUser: false,
    }
  },
  created() {
    this.getType()
    this.getPro()
    this.getDeptTree()
    this.ccPersonType()
    const params = this.$route.params && this.$route.params.data
    this.paramsData = JSON.parse(decryptCBC(params))
    if (this.paramsData.type === 'view') {
      //全部表单改为只读
    }
    let id = this.paramsData.id
    let version = this.paramsData.version
    if (id !== '0') {
      this.getDetail(id, version)
      //部分表单改为只读
      this.edit = true
    }
  },
  methods: {
    changeUser(e, index) {
      if (this.isChangingUser) return
      this.isChangingUser = true
      // Check if the selected value exists in any of the checkPerson arrays
      const isDuplicate = this.formData.processSetupItems.some(
        (item, idx) => idx !== index && item.checkPerson.includes(e[e.length - 1])
      )

      if (isDuplicate) {
        this.$message({
          message: '人员已在其他节点存在，请重新选择！',
          type: 'error',
        })

        // Remove the selected value from the current checkPerson array
        const itemIndex = this.formData.processSetupItems[index].checkPerson.indexOf(e[e.length - 1])
        if (itemIndex > -1) {
          this.formData.processSetupItems[index].checkPerson.splice(itemIndex, 1)
        }
      } else {
        // Add the selected value to the current checkPerson array if not already present
        if (!this.formData.processSetupItems[index].checkPerson.includes(e[e.length - 1])) {
          this.formData.processSetupItems[index].checkPerson.push(e[e.length - 1])
        }
      }

      this.isChangingUser = false // Reset the flag
      console.log('formData:', this.formData)
    },
    //检查单位名称是否存在
    async checkIsExistFlowName() {
      const params = {
        flowName: this.formData.flowName,
      }
      try {
        const response = await checkIsExistFlowName(params)
        if (response.code === 500) {
          this.$message({
            message: response.msg,
            type: 'error',
          })
          // 返回 false 或者其他值，表示单位名称已存在
          return false
        } else {
          // 返回 true 或者其他值，表示单位名称不存在重复
          return true
        }
      } catch (error) {
        return false
      }
    },
    //获取审批业务类型下拉框
    getType() {
      let params = {}
      queryTheApprovalServiceType(params).then(response => {
        this.flowOptions = response.data
      })
    },
    //获取工程下拉框
    getPro() {
      const params = {}
      getProName(params).then(response => {
        this.proOptions = response.data
      })
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data
      })
    },
    change(e) {
      if (e === 2 || e === '2') {
        // 通用审批流
        const params = {
          type: 2,
        }
        this.formData.businessType = ''
        this.formData.proId = ''
        queryTheApprovalServiceType(params).then(response => {
          this.flowOptions = response.data
          this.formData.resource = 1
        })
      } else {
        this.formData.resource = 2
      }
    },
    changeType(e) {
      const params = {
        proId: e,
        type: 1,
      }
      queryTheApprovalServiceType(params).then(response => {
        this.flowOptions = response.data
      })
    },
    clearPro() {
      this.formData.proId = ''
      this.formData.businessType = ''
    },
    clearBusiness() {
      this.formData.businessType = ''
    },
    /** 选择部门获取该部门人员 */
    UserType(e) {
      console.log(JSON.stringify(e))
      const params = {
        id: e.id,
      }
      personnelDropDownBox(params).then(response => {
        this.userOptions = response.data
      })
    },
    /** 抄送人员下拉框 */
    ccPersonType() {
      const params = {
        id: '',
      }
      personnelDropDownBox(params).then(response => {
        this.ccPersonOptions = response.data
        this.userOptions = response.data
      })
    },
    addAddressOption() {
      this.formData.processSetupItems.push({
        nodeName: '',
        deptId: undefined,
        checkPerson: '',
        examineTypes: '',
        finalJudgment: '0',
      })
    },
    removeLastItem(index) {
      this.formData.processSetupItems.splice(index, 1)
    },
    //提交承包商表单
    async submitConsForm() {
      let text =
        '<span style="font-size: 14px;font-weight: bold">是否提交审批流程配置？</span>' +
        '<br/><span style="font-size: 12px">提交完成，会重置当前审核流！！！</span>'
      if (!this.edit) {
        text = '<span style="font-size: 14px;font-weight: bold">是否提交审批流程配置？</span>'
      }
      this.$modal
        .confirm(text)
        .then(function () {
          return true
        })
        .then(() => {
          this.submitForm()
        })
        .catch(() => {
          this.loading = false
        })
    },
    submitForm() {
      console.log('formData:', JSON.stringify(this.formData.processSetupItems[0].checkPerson))
      //去除processSetupItems中checkPerson 的null值
      this.formData.processSetupItems.forEach(item => {
        item.checkPerson = item.checkPerson.filter(
          person => person !== null && person !== undefined && person !== 'null'
        )
      })
      console.log('formData:', JSON.stringify(this.formData.processSetupItems[0].checkPerson))
      // return
      this.$refs['elForm'].validate(async valid => {
        if (!valid) {
          this.$nextTick(() => {
            let isError = document.getElementsByClassName('is-error')
            isError[0].scrollIntoView({
              // 滚动到指定节点
              // 值有start,center,end，nearest，当前显示在视图区域中间
              block: 'center',
              // 值有auto、instant,smooth，缓动动画（当前是慢速的）
              behavior: 'smooth',
            })
          })
          return false
        } else {
          const id = this.paramsData.id
          if (id !== '0') {
            // TODO 修改
            this.formData.examineId = id
            updateExamine(this.formData)
              .then(response => {
                this.$modal.msgSuccess('修改成功')
                this.$tab.closePage()
              })
              .catch(error => {
                this.$modal.msgError('修改失败')
              })
          } else {
            // TODO 新增
            addExamine(this.formData)
              .then(response => {
                if (response.msg === '该审核流已存在') {
                  this.$modal.msgError('该审核流已存在')
                  return
                }
                this.$modal.msgSuccess('新增成功')
                this.$tab.closePage()
              })
              .catch(error => {
                this.$modal.msgError('新增失败')
              })
          }
        }
      })
    },
    getDetail(id, version) {
      this.loading = true
      // TODO 获取数据
      getExamine(id, version).then(response => {
        console.log('response:', response.data)
        this.formData = response.data
        if (this.formData.examineType == '1') {
          this.formData.resource = 2
        } else {
          this.formData.resource = 1
        }
        this.loading = false
      })
    },
  },
}
</script>

<style scoped lang="scss">
.el-radio__label {
  font-size: 18px;
  padding-left: 10px;
}

.arrow-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.line {
  width: 2px;
  height: 40px;
  background-color: black;
}

.arrow-down {
  width: 0;
  height: 0;
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-top: 10px solid black;
}
.treeselectMain .vue-treeselect__menu {
  // max-height: 200px !important;
  z-index: 2147483690 !important;
}
::v-deep .vue-treeselect__menu {
  // max-height: 200px !important;
}
</style>
