<!--
@name: 审批配置-编辑页
@author: 张泽贤
@time: 2022-06-13
@doc: PROLOG_UPCloudSolutionForTMS__v1.2.1_基础配置_1.2.2
-->
<template>
    <p-card class="full-card-panel">
      <a-space slot="title" >
        <a-icon type="arrow-left" style="color: #1990ff" @click="back" />
        审批配置-{{ typeTitle }}
      </a-space>
      <p-button slot="extra" :disabled="spinning" v-show="type === 'add' || type === 'edit'" type="primary" @click="onSave">保存</p-button>
        <p-spin class="spin-pull" :spinning="spinning">


        <a-divider orientation="left">基本信息</a-divider>
        <p-form-model ref="ruleForm" class="plg-grid-from" :model="form" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }" :rules="rules">
          <a-row>
            <a-col :span="6">
              <p-form-model-item label="名称" prop="approvalName">
                <p-input v-model="form.approvalName" :disabled="type !== 'add'" />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="审批流程" prop="approvalFlowType">
                <p-select v-model="form.approvalFlowType" :options="options.APPROVAL_FLOW_TYPE" :disabled="type !== 'add'" @change="approvalFlowTypeChange" />
              </p-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <p-form-model-item label="备注" prop="memo" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
                <p-input v-model="form.memo" :disabled="!isFocus" />
              </p-form-model-item>
            </a-col>
          </a-row>

          <a-divider orientation="left">满足条件</a-divider>
          <div v-if="form.approvalFlowType && form.approvalFlowType !== 2 && form.approvalFlowType !== 8">
            <p-button type="primary" @clickSync="onAddBtn" v-if="isFocus && form.approvalFlowType !== 1">新增</p-button>
            <a-row v-for="(item, index) in approvalConditions" :key="index">
              <a-col :span="6">
                <p-form-model-item label="" prop="approvalConditionType" :label-col="{ span: 0 }" :wrapper-col="{ span: 24 }">
                  <p-select v-model="item.approvalConditionType" :options="APPROVAL_CONDITION_TYPE" allowClear @change="(value) => approvalConditionTypeChange(value, item)" :disabled="!isFocus" />
                </p-form-model-item>
              </a-col>
              <a-col :span="6" style="margin-left: 10px" v-show="item.approvalConditionType !== 8 && item.approvalConditionType !== 9">
                <p-form-model-item label="" prop="approvalConditionValue" :label-col="{ span: 0 }" :wrapper-col="{ span: 24 }">
                  <p-select v-model="item.approvalConditionValue" :options="approvalConditionValueEnums[item.approvalConditionType]" :disabled="!isFocus" />
                </p-form-model-item>
              </a-col>
              <a-col :span="6" style="margin-left: 10px" v-show="(item.approvalConditionType === 2 || item.approvalConditionType === 3) && item.approvalConditionValue === 1">
                <p-form-model-item label="" prop="unitName" :label-col="{ span: 0 }" :wrapper-col="{ span: 24 }">
                  <p-search-modal v-model="item.unitName" v-bind="customerAttr" @change="(...args) => onFormChange('customer', item, ...args)" :disabled="!isFocus" />
                </p-form-model-item>
              </a-col>
              <a-col :span="6" style="margin-left: 10px" v-show="(item.approvalConditionType === 2 || item.approvalConditionType === 3) && item.approvalConditionValue === 2">
                <p-form-model-item label="" prop="unitName" :label-col="{ span: 0 }" :wrapper-col="{ span: 24 }">
                  <p-search-modal v-model="item.unitName" v-bind="branchAttr" @change="(...args) => onFormChange('branch', item, ...args)" :disabled="!isFocus" />
                </p-form-model-item>
              </a-col>
              <a-col :span="6" style="margin-left: 10px" v-show="(item.approvalConditionType === 2 || item.approvalConditionType === 3) && item.approvalConditionValue === 3">
                <p-form-model-item label="" prop="unitName" :label-col="{ span: 0 }" :wrapper-col="{ span: 24 }">
                  <p-search-modal v-model="item.unitName" v-bind="supplierAttr" @change="(...args) => onFormChange('supplier', item, ...args)" :disabled="!isFocus" />
                </p-form-model-item>
              </a-col>
              <a-col :span="6" style="margin-left: 10px" v-show="item.approvalConditionType === 8">
                <p-form-model-item label="" prop="unitName" :label-col="{ span: 0 }" :wrapper-col="{ span: 24 }">
                  <p-search-modal v-model="item.unitName" v-bind="$data.$formItems.consignorAttr" @change="(...args) => onFormChange('consignor', item, ...args)" :disabled="!isFocus" />
                </p-form-model-item>
              </a-col>
              <a-col :span="6" style="margin-left: 10px" v-show="item.approvalConditionType === 9">
                <p-form-model-item label="" prop="unitName" :label-col="{ span: 0 }" :wrapper-col="{ span: 24 }">
                  <departmenTree :departmentCode="departmentCode" @getDepartment="(value) => getDepartment(value, item)" :disabled="!isFocus"></departmenTree>
                </p-form-model-item>
              </a-col>
              <a-col :span="2">
                <p-form-model-item style="text-align: right">
                  <a-space>
                    <p-button type="danger" @click="onDelBtn(index)" v-if="isFocus && form.approvalFlowType !== 1">删除</p-button>
                  </a-space>
                </p-form-model-item>
              </a-col>
            </a-row>
          </div>
        </p-form-model>
      <!-- <div v-if="type === 'node'">
        <a-divider orientation="left">节点设置</a-divider>
      </div> -->
      <p-card style="margin-top: 20px" v-if="type === 'node'">
        <div slot="title">节点设置</div>
        <div slot="extra">
          <a-space>
            <p-button type="primary" @click="onConfigureAdd">新增</p-button>
            <p-button type="primary" @click="onConfigureSave">保存</p-button>
          </a-space>
        </div>
        <p-table ref="editTable" dragle bordered row-key="nodeId" hasRowSelectCheck :data-source.sync="dataSource" :rowSelectType="false" :autoLoad="false" :pagination="false">
          <p-table-column data-index="roleNames" title="角色">
            <template slot-scope="text, record">
              <p-search-modal v-model="record.roleNames" v-bind="roleAttr" @change="(...args) => onTableChange('role', record, ...args)" :disabled="record.nodeApproverType !== 1" />
            </template>
          </p-table-column>
          <p-table-column data-index="userNames" title="用户">
            <template slot-scope="text, record">
              <p-search-modal v-model="record.userNames" v-bind="userAttr" @change="(...args) => onTableChange('user', record, ...args)" :disabled="record.nodeApproverType !== 2" />
            </template>
          </p-table-column>
          <p-table-column data-index="status" title="节点状态">
            <template slot-scope="text, record">
              <p-select v-model="record.status" :options="options.APPROVAL_STATUS" />
            </template>
          </p-table-column>
          <p-table-column data-index="nodeApprovalType" title="多人审批方式">
            <template slot-scope="text, record">
              <p-select v-model="record.nodeApprovalType" :options="options.NODE_APPROVAL_TYPE" allowClear />
            </template>
          </p-table-column>
          <p-table-column key="action" title="操作">
            <template slot-scope="record">
              <a-space>
                <a @click.stop="onConfigureDown(record._row_count - 1)" :disabled="record._row_count === dataSource.length">下移</a>
                <a @click.stop="onConfigureUp(record._row_count - 1)" :disabled="record._row_count === 1">上移</a>
                <a @click.stop="onConfigureDel(record._row_count - 1, record)">删除</a>
              </a-space>
            </template>
          </p-table-column>
          <p-table-column data-index="nodeApproverType" title="审批人">
            <template slot-scope="text, record">
              <a-radio-group v-model="record.nodeApproverType" @change="(e) => nodeApproverTypeChange(e, record)">
                <a-radio v-for="(item, index) in options.NODE_APPROVER_TYPE" :key="index" :value="item.value">{{ item.label }}</a-radio>
              </a-radio-group>
            </template>
          </p-table-column>
        </p-table>
      </p-card>
    </p-spin>

    </p-card>
</template>

<script>
import * as $formItems from '@/blocks/components/searchModalConfig/index'
import departmenTree from '@/blocks/components/formConfig/index.departmenTree.vue'

import { Add, Update, View, approval_node_config, approval_node_delete, approval_node_query } from './api'

export default {
  components: { departmenTree },
  props: {
    type: '',
    editId: {
      type: String,
      default: '',
    },
    options: {
      type: Object,
      default: () => ({}),
    },
  },
  computed: {
    typeTitle() {
      const dictionary = {
        add: '新增',
        edit: '编辑',
        view: '查看',
        node: '配置节点',
      }
      return dictionary[this.type] || this.type
    },
    isFocus() {
      return this.type === 'add' || this.type === 'edit'
    },
    consignorAttr() {
      let consignorAttr = $formItems.consignorAttr
      consignorAttr.tableConfig.rowSelectType = 2
      return consignorAttr
    },
    roleAttr() {
      let roleAttr = $formItems.roleAttr
      roleAttr.tableConfig.rowSelectType = 2
      return roleAttr
    },
    userAttr() {
      let userAttr = $formItems.userAttr
      userAttr.tableConfig.rowSelectType = 2
      return userAttr
    },
    customerAttr() {
      let customerAttr = $formItems.customerAttr
      customerAttr.tableConfig.rowSelectType = 2
      return customerAttr
    },
    branchAttr() {
      let branchAttr = $formItems.branchAttr
      branchAttr.tableConfig.rowSelectType = 2
      return branchAttr
    },
    supplierAttr() {
      let supplierAttr = $formItems.supplierNoConsignorAttr
      supplierAttr.tableConfig.rowSelectType = 2
      return supplierAttr
    },
  },
  data() {
    return {
      $formItems,
      spinning: false,
      form: {
        approvalName: '',
        approvalFlowType: '',
        cargoOwnerId: '',
        cargoOwnerCode: '',
        cargoOwnerName: '',
        memo: '',
      },
      rules: {
        approvalName: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        approvalFlowType: [{ required: true, message: '审批流程不能为空', trigger: 'change' }],
      },

      approvalConditions: [],
      approvalConditionValueEnums: {
        '': [],
        1: this.options.DELIVERY_METHOD_TYPE, // 配送方式
        2: this.options.SHIPPER_TYPE,
        3: this.options.CONSIGNEE_TYPE,
        4: this.options.ORDER_TYPE,
        5: this.options.ORDER_BUSINESS_TYPE,
        6: this.options.TRANSPORT_TYPE,
        7: this.options.TEMPERATURE_REQUIREMENT,
        8: [],
        9: [],
      },
      APPROVAL_CONDITION_TYPE: [],

      dataSource: [],

      departmentCode: '', // 部门code
    }
  },
  mounted() {
    if (this.editId) {
      this.spinning = true
      View({ approvalId: this.editId })
        .then((res) => {
          if (res.success) {
            this.form = { ...res.data }
            this.approvalConditions = [...res.data.approvalConditionViewDTOS]
            delete this.form.approvalConditionViewDTOS
            if (this.form.approvalFlowType === 1) {
              this.APPROVAL_CONDITION_TYPE = [{ value: 8, label: '货主' }]
            } else {
              this.APPROVAL_CONDITION_TYPE = [...this.options.APPROVAL_CONDITION_TYPE]
            }
            this.APPROVAL_CONDITION_TYPE_INIT()
            // 处理部门渲染
            this.$nextTick(() => {
              this.approvalConditions.forEach((item) => {
                if (item.approvalConditionType === 9) {
                  this.departmentCode = item.unitCode
                }
              })
            })
          } else {
            this.$exception(res)
          }
        })
        .finally(() => {
          this.spinning = false
        })

      if (this.type === 'node') {
        approval_node_query({ approvalId: this.editId })
          .then((res) => {
            if (res.success) {
              this.dataSource = res.data.approvalNodeQueryDTOS.map((item) => {
                return item
              })
            } else {
              this.$exception(res)
            }
          })
          .finally(() => {
            this.spinning = false
          })
      }
    }
  },
  methods: {
    back() {
      this.$emit('back')
    },
    onSave() {
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) return
        if (this.type === 'add') return this.onAdd({ ...this.form, approvalConditionAddVOS: this.approvalConditions })
        if (this.type === 'edit') {
          let self = this
          this.$confirm({
            title: '是否保存',
            onOk() {
              return new Promise((resolve, reject) => {
                self.spinning = true
                Update({ ...self.form, approvalConditionUpdateVOS: self.approvalConditions })
                  .then((res) => {
                    if (res.success) {
                      self.$message.success(res.message)
                      self.$emit('back')
                      resolve()
                    } else {
                      self.$exception(res)
                      resolve()
                    }
                  })
                  .finally(() => {
                    self.spinning = false
                    reject()
                  })
              })
            },
          })
        }
        return
      })
    },
    onAdd(params) {
      this.spinning = true
      Add(params)
        .then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.$emit('back')
          } else {
            this.$exception(res)
          }
        })
        .finally(() => {
          this.spinning = false
        })
    },

    // 下移
    onConfigureDown(index) {
      this.dataSource[index] = this.dataSource.splice(index + 1, 1, this.dataSource[index])[0]
    },
    // 上移
    onConfigureUp(index) {
      this.dataSource[index] = this.dataSource.splice(index - 1, 1, this.dataSource[index])[0]
    },
    // 删除
    onConfigureDel(index, record) {
      if (!record.nodeId.includes('add')) {
        this.spinning = true
        approval_node_delete({ approvalId: this.editId, nodeId: record.nodeId })
          .then((res) => {
            if (res.success) {
              this.$message.success(res.message)
              this.dataSource.splice(index, 1)
            } else {
              this.$exception(res)
            }
          })
          .finally(() => {
            this.spinning = false
          })
      } else {
        this.dataSource.splice(index, 1)
      }
    },
    // 节点设置新增
    onConfigureAdd() {
      this.dataSource.push({
        nodeId: 'add' + new Date().getTime(),
        status: 1,
        nodeApprovalType: '',
        nodeApproverType: 1,
      })
    },
    // 节点设置保存
    onConfigureSave() {
      let list = JSON.parse(JSON.stringify(this.dataSource)).map((item, index) => {
        if (item.nodeId.includes('add')) {
          delete item.nodeId
        }
        item.approvalId = this.editId
        item.nodeOrder = index + 1
        return item
      })

      for (let index = 0; index < list.length; index++) {
        const element = list[index]
        if (element.nodeApproverType === 1 && !element.roleNames) {
          this.$message.error('请选择角色')
          return false
        }
        if (element.nodeApproverType === 2 && !element.userNames) {
          this.$message.error('请选择用户')
          return false
        }
        if (!element.status) {
          this.$message.error('请选择节点状态')
          return false
        }
        if (!element.nodeApprovalType) {
          this.$message.error('请选择多人审批方式')
          return false
        }
      }

      this.spinning = true
      approval_node_config(list)
        .then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.$emit('back')
          } else {
            this.$exception(res)
          }
        })
        .finally(() => {
          this.spinning = false
        })
    },

    onFormChange(name, item, ...args) {
      if (!args[1]) {
        this.$set(item, 'unitId', '')
        this.$set(item, 'unitCode', '')
        this.$set(item, 'unitName', '')
        return
      }
      if (name === 'consignor') {
        let cargoOwnerIdList = [],
          cargoOwnerCodeList = []
        args[2].forEach((item) => {
          cargoOwnerIdList.push(item.cargoOwnerId)
          cargoOwnerCodeList.push(item.cargoOwnerCode)
        })
        this.$set(item, 'unitName', args[1])
        this.$set(item, 'unitCode', cargoOwnerCodeList.join(','))
        this.$set(item, 'unitId', cargoOwnerIdList.join(','))
      } else {
        let idList = [],
          codeList = []
        args[2].forEach((item) => {
          idList.push(item.id)
          codeList.push(item.code)
        })
        this.$set(item, 'unitId', idList.join(','))
        this.$set(item, 'unitCode', codeList.join(','))
        this.$set(item, 'unitName', args[1])
      }
    },
    onTableChange(name, record, ...args) {
      if (name === 'role') {
        let approvalNodeRoleVOs = args[2].map((item) => {
          return {
            approverRoleId: item.id,
            approverRoleName: item.name,
          }
        })
        this.$set(record, 'roleNames', args[1])
        this.$set(record, 'approvalNodeRoleVOs', approvalNodeRoleVOs)
      } else if (name === 'user') {
        let approvalNodeUserVOs = args[2].map((item) => {
          return {
            approverUserId: item.id,
            approverUserName: item.nickname,
          }
        })
        this.$set(record, 'userNames', args[1])
        this.$set(record, 'approvalNodeUserVOs', approvalNodeUserVOs)
      }
    },
    nodeApproverTypeChange(e, record) {
      this.$set(record, 'roleNames', '')
      this.$set(record, 'approvalNodeRoleVOs', [])
      this.$set(record, 'userNames', '')
      this.$set(record, 'approvalNodeUserVOs', [])
    },

    onAddBtn() {
      this.approvalConditions.push({
        approvalConditionType: '',
        approvalConditionValue: '',
        unitId: '',
        unitCode: '',
        unitName: '',
      })
    },
    onDelBtn(index) {
      this.approvalConditions.splice(index, 1)
      this.APPROVAL_CONDITION_TYPE_INIT()
    },
    approvalConditionTypeChange(value, item) {
      item.approvalConditionValue = ''
      item.unitId = ''
      item.unitCode = ''
      item.unitName = ''
      this.APPROVAL_CONDITION_TYPE_INIT()
    },
    // 更新APPROVAL_CONDITION_TYPE
    APPROVAL_CONDITION_TYPE_INIT() {
      let selectList = this.approvalConditions.map((item) => item.approvalConditionType)
      this.APPROVAL_CONDITION_TYPE.forEach((item) => {
        if (selectList.includes(item.value)) {
          item.disabled = true
        } else {
          item.disabled = false
        }
      })
    },
    // 审批流程change
    approvalFlowTypeChange(value) {
      this.approvalConditions = [
        {
          approvalConditionType: '',
          approvalConditionValue: '',
          unitId: '',
          unitCode: '',
          unitName: '',
        },
      ]
      if (value === 1) {
        this.APPROVAL_CONDITION_TYPE = [{ value: 8, label: '货主' }]
      } else {
        this.APPROVAL_CONDITION_TYPE = [...this.options.APPROVAL_CONDITION_TYPE]
      }
      this.APPROVAL_CONDITION_TYPE_INIT()
    },
    // 部门change
    getDepartment(value, item) {
      this.departmentCode = value.departmentCode
      item.unitId = value.departmentId
      item.unitCode = value.departmentCode
      item.unitName = value.departmentName
    },
  },
}
</script>

<style lang="less">
.ant-select {
  width: 100%;
}
</style>