<template>
  <!-- 任务代理 dialog -->
  <div>
    <el-dialog
      top="50px"
      width="800px"
      :title="dialogTitle"
      :visible="delegateDialogVisible"
      :close-on-click-modal="false"
      @close="closeDialog"
    >
      <div v-if="!formDisabled" class="form-edit">
        <el-form
          ref="form"
          v-form
          data-vv-scope="delegateForm"
          :rules="rules"
          :model="formData"
          label-width="100px"
        >
          <el-form-item label="标题：" prop="subject">
            <el-input
              v-model="formData.subject"
              clearable
              show-word-limit
              maxlength="50"
            ></el-input>
          </el-form-item>

          <el-form-item label="被委托人：" prop="users">
            <ht-user-selector-input
              v-model="formData.users"
              single
              quick-search-props="fullname,account"
              :append-to-body="true"
              permission="w"
              :config="{ id: 'formData.agentId', fullname: 'formData.agent' }"
            ></ht-user-selector-input>
          </el-form-item>

          <el-form-item label="开始日期：" prop="startDate">
            <el-date-picker
              v-model="formData.startDate"
              type="datetime"
              placeholder="选择开始日期"
              format="yyyy-MM-dd HH:mm:ss"
            ></el-date-picker>
          </el-form-item>

          <el-form-item label="结束日期：" prop="endDate">
            <el-date-picker
              v-model="formData.endDate"
              type="datetime"
              placeholder="选择结束日期"
              format="yyyy-MM-dd HH:mm:ss"
            ></el-date-picker>
          </el-form-item>

          <el-form-item label="委托类型：" prop="type">
            <el-radio v-model="formData.type" :label="1">全权委托</el-radio>
            <el-radio v-model="formData.type" :label="2">部分委托</el-radio>
          </el-form-item>

          <el-form-item v-if="formData.type == 2" label="委托流程：">
            <el-button
              size="mini"
              icon="el-icon-plus"
              style="margin-bottom: 10px"
              @click="selectFlow"
            >
              新增
            </el-button>
            <div v-if="formData.defList.length">
              <el-table
                stripe
                border
                size="mini"
                :data="formData.defList"
                max-height="260"
              >
                <el-table-column
                  prop="flowName"
                  label="流程名称"
                ></el-table-column>

                <el-table-column
                  prop="flowKey"
                  label="流程key"
                ></el-table-column>

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

          <el-form-item label="是否启用：" prop="isEnabled">
            <el-radio v-model="formData.isEnabled" label="Y">启用</el-radio>
            <el-radio v-model="formData.isEnabled" label="N">禁用</el-radio>
          </el-form-item>
        </el-form>
      </div>
      <div v-if="!formDisabled" slot="footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submitForm('form')">保存</el-button>
      </div>

      <div v-else class="form-check">
        <div class="item">
          <label>标题：</label>
          <div class="value">{{ formData.subject }}</div>
        </div>
        <div class="item">
          <label>被委托人：</label>
          <div class="value">{{ formData.users }}</div>
        </div>
        <div class="item">
          <label>开始日期：</label>
          <div class="value">{{ formData.startDate }}</div>
        </div>
        <div class="item">
          <label>结束日期：</label>
          <div class="value">{{ formData.endDate }}</div>
        </div>
        <div class="item">
          <label>委托类型：</label>
          <div class="value">
            {{ formData.type == 1 ? '全部委托' : '部分委托' }}
          </div>
        </div>

        <div v-if="formData.defList.length" class="item">
          <label>委托流程：</label>
          <div class="table value">
            <el-table
              border
              size="mini"
              :data="formData.defList"
              max-height="260"
            >
              <el-table-column
                prop="flowName"
                label="流程名称"
              ></el-table-column>

              <el-table-column prop="flowKey" label="流程key"></el-table-column>
            </el-table>
          </div>
        </div>
        <div class="item">
          <label>是否启用：</label>
          <div class="value">{{ formData.isEnabled | getStatus }}</div>
        </div>
      </div>
    </el-dialog>

    <flow-select-dialog
      ref="flowSelect"
      dialog-title="委托流程"
      :agent="true"
      @get-selected-rows="getSelectedRows"
    />
  </div>
</template>

<script>
  import { agentSave, getAgentDetail } from '@/api/personal'
  import FlowSelectDialog from './FlowSelectDialog'
  export default {
    name: 'DelegateDialog',
    components: {
      FlowSelectDialog,
    },
    filters: {
      getStatus(val) {
        return val === 'Y' ? '启用' : val === 'N' ? '禁用' : ''
      },
    },
    props: {
      editRowId: {
        type: String,
        default: '',
      },
      dialogTitle: {
        type: String,
        default: '添加委托',
      },
      delegateDialogVisible: {
        type: Boolean,
        default: false,
      },
      formDisabled: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {
        formData: {
          users: '',
          agent: '',
          agentId: '',
          type: '',
          subject: '',
          startDate: '',
          endDate: '',
          isEnabled: '',
          defList: [],
        },

        rules: {
          users: [
            { required: true, message: '请选择被委托人', trigger: 'blur' },
          ],
          type: [
            { required: true, message: '请选择委托类型', trigger: 'blur' },
          ],
          subject: [{ required: true, message: '请输入标题', trigger: 'blur' }],
          startDate: [
            { required: true, message: '请输入开始时间', trigger: 'blur' },
          ],
          endDate: [
            { required: true, message: '请输入结束时间', trigger: 'blur' },
          ],
          isEnabled: [
            { required: true, message: '请选择是否有效', trigger: 'blur' },
          ],
        },
      }
    },
    watch: {
      delegateDialogVisible(val) {
        if (val) {
          if (this.editRowId) {
            getAgentDetail(this.editRowId).then((res) => {
              this.formData = { ...res }
              this.formData.users = res.agent
            })
          } else {
            this.formDataReset()
          }
        }
      },
    },
    methods: {
      closeDialog() {
        this.$emit('update:delegateDialogVisible', false)
        this.$emit('recoverState')
        if (!this.editRowId) {
          this.$refs.form.resetFields()
        }
      },
      selectFlow() {
        this.$refs.flowSelect.showDialog()
      },
      getSelectedRows(rows) {
        this.formData.defList = rows
      },
      removeFlow($index) {
        this.formData.defList.splice($index, 1)
      },
      formDataReset() {
        this.formData = {
          users: '',
          agent: '',
          agentId: '',
          type: '',
          subject: '',
          startDate: '',
          endDate: '',
          isEnabled: '',
          defList: [],
        }
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            const { type, defList, startDate, endDate } = this.formData
            if (+new Date(startDate) > +new Date(endDate)) {
              this.$message.warning('结束时间要大于开始时间！')
              return
            }

            if (type == 2 && defList.length < 1) {
              this.$message.warning('请选择要委托的流程！')
              return
            }

            const { username } = this.$store.state.user
            if (username == this.formData.agent) {
              this.$message.warning('不能指定自己为委托人！')
              return
            }

            const moment = require('moment')
            this.formData.startDate = moment(startDate).format(
              'YYYY-MM-DD HH:mm:ss'
            )
            this.formData.endDate = moment(endDate).format(
              'YYYY-MM-DD HH:mm:ss'
            )

            const jsonData = { ...this.formData }
            delete jsonData.users
            agentSave(jsonData).then((res) => {
              if (res.state) {
                this.closeDialog()
                this.$emit('agentChange')
                this.$message.success(res.message)
              } else {
                this.$message.error(res.message)
              }
            })
          } else {
            this.$message.warning('您输入表单信息有误，请重新填写!')
          }
        })
      },
    },
  }
</script>

<style lang="scss" scoped>
  ::v-deep .el-form-item {
    .el-form-item__label {
      text-align: left;
    }
  }
  .form-edit {
    margin: 0 30px;
  }
  .form-check {
    margin: 10px 48px 32px 48px;
    .item {
      display: flex;
      label {
        width: 80px;
        color: #888;
        text-align: left;
      }
      .value {
        color: #333;
      }
      .table {
        width: calc(100% - 90px);
      }
      &:not(:last-child) {
        margin-bottom: 24px;
      }
    }
  }
</style>
