<template>
  <!-- 领导秘书 dialog -->
  <div>
    <el-dialog
      top="50px"
      width="800px"
      :title="dialogTitle"
      :visible="secretaryDialogVisible"
      :close-on-click-modal="false"
      @close="closeDialog"
    >
      <el-form v-form :model="formData" label-width="120px">
        <el-form-item label="秘书姓名：">
          <ht-user-selector-input
            v-model="formData.secretaryName"
            quick-search-props="fullname,account"
            :append-to-body="true"
            :config="{ id: 'formData.secretaryId' }"
          ></ht-user-selector-input>
        </el-form-item>

        <el-form-item label="是否启用：">
          <el-radio-group v-model="formData.enabled">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="共享权限：">
          <el-checkbox-group v-model="shareRights">
            <el-checkbox
              v-for="item in shareRightList"
              :key="item.value"
              :label="item.value"
            >
              {{ item.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="共享类型：">
          <el-radio-group v-model="formData.shareType" @change="tableData = []">
            <el-radio label="1">流程定义</el-radio>
            <el-radio label="2">流程分类</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item :label="`${labelName}：`">
          <el-button size="mini" icon="el-icon-plus" @click="showFlowDialog()">
            添加
          </el-button>

          <div v-if="tableData.length" class="table">
            <el-table border :data="tableData" max-height="300">
              <el-table-column
                :label="colName"
                prop="flowName"
              ></el-table-column>

              <el-table-column label="操作" width="150">
                <template #default="{ $index }">
                  <el-button type="text" @click="removeFlow($index)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
      </el-form>

      <div slot="footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </div>
    </el-dialog>

    <flow-select-dialog
      ref="flowSelect"
      dialog-title="选择流程"
      :auth-filter="authFilter"
      @get-selected-rows="getSelectedRows"
    />
    <flow-type-select-tree
      ref="flowTree"
      @get-selected-rows="getSelectedRows"
    />
  </div>
</template>

<script>
  import { saveSecretary } from '@/api/personal'
  import FlowSelectDialog from './FlowSelectDialog'
  import FlowTypeSelectTree from './FlowTypeSelectTree'
  export default {
    name: 'SecretaryDialog',
    components: {
      FlowSelectDialog,
      FlowTypeSelectTree,
    },
    props: {
      editRow: {
        type: Object,
        default: null,
      },
      secretaryDialogVisible: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {
        tableData: [],
        shareRights: [],
        dialogTitle: '',
        formData: {
          secretaryId: '',
          secretaryName: '',
          enabled: '1',
          shareType: '1',
          shareRight: '',
        },

        shareRightList: [
          { label: '流程发起', value: '1' },
          { label: '任务审批', value: '2' },
        ],
        authFilter: true,
      }
    },
    computed: {
      labelName() {
        return this.formData.shareType == '1' ? '共享流程' : '共享分类'
      },
      colName() {
        return this.formData.shareType == '1' ? '流程名称' : '分类名称'
      },
    },
    watch: {
      secretaryDialogVisible(val) {
        if (val) {
          if (this.editRow) {
            this.dialogTitle = '编辑秘书'
            this.formData = { ...this.editRow }
            this.shareRights = this.editRow.shareRight.split(',')

            this.tableData = []
            const flowKeys = this.editRow.shareKey.split(',')
            const flowNames = this.editRow.shareName.split(',')
            for (let i = 0; i < flowKeys.length; i++) {
              this.tableData.push({
                flowKey: flowKeys[i],
                flowName: flowNames[i],
              })
            }
          } else {
            this.dialogTitle = '添加秘书'
            this.formDataReset()
          }
        }
      },
      shareRights: {
        handler: function (newVal) {
          let authFilter = true
          if (newVal && newVal.includes('2')) {
            authFilter = false
          }
          this.authFilter = authFilter
        },
      },
    },
    methods: {
      closeDialog() {
        this.$emit('update:secretaryDialogVisible', false)
      },
      showFlowDialog() {
        if (this.formData.shareType == '1') {
          this.$refs.flowSelect.showDialog()
        } else {
          this.$refs.flowTree.openDialog()
        }
      },
      getSelectedRows(rows) {
        this.tableData = rows
      },
      removeFlow(index) {
        this.tableData.splice(index, 1)
      },
      formDataReset() {
        this.tableData = []
        this.shareRights = []
        this.formData = {
          secretaryId: '',
          secretaryName: '',
          enabled: '1',
          shareType: '1',
          shareRight: '',
        }
      },
      handleConfirm() {
        const { username, userId } = this.$store.state.user
        const { secretaryId, secretaryName } = this.formData
        if (!secretaryId) {
          this.$message.warning('请选择秘书')
          return
        }

        let someData = secretaryId.split(',').some((item) => {
          return item == userId
        })

        if (someData) {
          this.$message.warning('不能指定自己为秘书')
          return
        }
        if (!this.shareRights.length) {
          this.$message.warning('请选择要共享的权限')
          return
        }
        if (!this.tableData.length) {
          this.$message.warning(`请选择要委托的${this.labelName}`)
          return
        }

        const flowKeys = []
        const flowNames = []
        this.tableData.forEach((item) => {
          flowKeys.push(item.flowKey)
          flowNames.push(item.flowName)
        })
        this.formData.shareKey = flowKeys.join(',')
        this.formData.shareName = flowNames.join(',')
        this.formData.shareRight = this.shareRights.join(',')

        saveSecretary(this.formData).then((res) => {
          if (res.state) {
            this.closeDialog()
            this.$emit('secretary-change')
            this.$message.success(res.message)
          } else {
            this.$message.error(res.message)
          }
        })
      },
    },
  }
</script>

<style lang="scss" scoped>
  .table {
    margin-top: 10px;
  }
</style>
