<!--
@description: 基础表单
@Author: linqian
@Date: 2021-07-10
-->
<template>
  <div>
    <el-form :class="isDetail ? '' : 'v-form-text'" ref="ruleForm" :model="sizeForm" :rules="rules" label-width="160px">
      <dg-row>
        <dg-col :span="12">
          <el-form-item label="审批类型：" prop="applyType">
            <div v-if="isDetail">{{ sizeForm.applyType }}</div>
            <div v-else>
              <dg-select
                :data="applyType"
                v-model="sizeForm.applyType"
                @change="handleChangeApproveType"
                :disabled="type == 'edit'"
              ></dg-select>
            </div>
          </el-form-item>
        </dg-col>
        <dg-col :span="12">
          <el-form-item label="流程名称：" prop="processName">
            <div v-if="isDetail">{{ sizeForm.processName }}</div>
            <div v-else>
              <dg-select
                :data="processNameType"
                v-model="sizeForm.processName"
                @change="handleChangeProcessName"
              ></dg-select>
            </div>
          </el-form-item>
        </dg-col>
        <dg-col :span="12" v-if="isDetail">
          <el-form-item label="流程编号：" prop="businessCode">
            <div>{{ sizeForm.businessCode }}</div>
          </el-form-item>
        </dg-col>
        <dg-col :span="12" v-if="isDetail">
          <el-form-item label="审批单编号：" prop="applicantId">
            <div>{{ sizeForm.applicantId }}</div>
          </el-form-item>
        </dg-col>
        <dg-col :span="12">
          <!-- 流程名称+申请人姓名+日期 -->
          <el-form-item label="审批单标题：" prop="applyTitle">
            <div v-if="isDetail">{{ sizeForm.applyTitle }}</div>
            <div v-else>
              <el-input v-model="sizeForm.applyTitle" :disabled="true"></el-input>
            </div>
          </el-form-item>
        </dg-col>
        <dg-col :span="12">
          <el-form-item label="申请人姓名：" prop="applicantName">
            <div v-if="isDetail">{{ sizeForm.applicantName }}</div>
            <div v-else>
              <el-input v-model="sizeForm.applicantName" :disabled="true"></el-input>
            </div>
          </el-form-item>
        </dg-col>
        <dg-col :span="12">
          <el-form-item label="申请人身份证号码：" prop="applicantIdcard">
            <div v-if="isDetail">{{ sizeForm.applicantIdcard }}</div>
            <div v-else>
              <el-input v-model="sizeForm.applicantIdcard" :disabled="true"></el-input>
            </div>
          </el-form-item>
        </dg-col>
        <dg-col :span="12">
          <el-form-item label="申请人手机号码：" prop="applicantPhoneNo">
            <div v-if="isDetail">{{ sizeForm.applicantPhoneNo }}</div>
            <div v-else>
              <el-input v-model="sizeForm.applicantPhoneNo"></el-input>
            </div>
          </el-form-item>
        </dg-col>
        <dg-col :span="12">
          <el-form-item label="申请人单位代码：" prop="applicantOrgCode">
            <div v-if="isDetail">{{ sizeForm.applicantOrgCode }}</div>
            <div v-else>
              <el-input v-model="sizeForm.applicantOrgCode" :disabled="true"></el-input>
            </div>
          </el-form-item>
        </dg-col>
        <dg-col :span="12">
          <el-form-item label="申请人单位名称：" prop="applicantOrgName">
            <div v-if="isDetail">{{ sizeForm.applicantOrgName }}</div>
            <div v-else>
              <el-input v-model="sizeForm.applicantOrgName" :disabled="true"></el-input>
            </div>
          </el-form-item>
        </dg-col>
        <dg-col :span="12" v-if="sizeForm.applyType == '1'">
          <el-form-item label="应用方：" prop="applyId">
            <div v-if="isDetail">{{ sizeForm.applyId }}</div>
            <div v-else>
              <dg-select :data="[]" v-model="sizeForm.applyId"></dg-select>
            </div>
          </el-form-item>
        </dg-col>
      </dg-row>
      <dg-row> </dg-row>
      <dg-row>
        <dg-col :span="8" v-if="isDetail">
          <el-form-item label="创建时间：">
            {{ sizeForm.createTime }}
          </el-form-item>
        </dg-col>
      </dg-row>
      <dg-row>
        <dg-col :span="24">
          <!-- <component :is="approveComponent"></component> -->
          <el-form-item label="审批内容：" class="self-form-item" prop="flowContent">
            <div style="display: flex" v-if="!isDetail">
              <el-input
                type="textarea"
                :autosize="{ minRows: 5 }"
                v-model="sizeForm.flowContent"
                :disabled="true"
              ></el-input>
              <dg-button style="margin-left: 10px" @click="handleChoice">选择</dg-button>
            </div>
            <div v-else>
              {{ sizeForm.flowContent }}
            </div>
          </el-form-item>
        </dg-col>
      </dg-row>
      <dg-row>
        <dg-col :span="24">
          <el-form-item prop="applyReason" label="申请理由：">
            <div v-if="isDetail">
              {{ sizeForm.applyReason }}
            </div>
            <div v-else>
              <el-input
                v-model="sizeForm.applyReason"
                type="textarea"
                maxlength="300"
                show-word-limit
                :autosize="{ minRows: 5 }"
              ></el-input>
            </div>
          </el-form-item>
        </dg-col>
        <!-- 数据资源访问权限 -->
        <div v-if="sizeForm.applyType == '2'">
          <dg-col :span="13">
            <el-form-item label="案件/事件/线索/被查询人员类别：" prop="userType" label-width="250px">
              <div v-if="isDetail">{{ sizeForm.userType }}</div>
              <div v-else>
                <dg-select :data="[]" v-model="sizeForm.userType"></dg-select>
              </div>
            </el-form-item>
          </dg-col>
          <dg-col :span="13">
            <el-form-item label="案件/事件/线索/被查询人员姓名：" prop="userName" label-width="250px">
              <div v-if="isDetail">{{ sizeForm.userName }}</div>
              <div v-else>
                <el-input v-model="sizeForm.userName"></el-input>
              </div>
            </el-form-item>
          </dg-col>
          <dg-col :span="13">
            <el-form-item label="案件/事件/线索/被查询人员编码：" prop="userCode" label-width="250px">
              <div v-if="isDetail">{{ sizeForm.userCode }}</div>
              <div v-else>
                <el-input :data="[]" v-model="sizeForm.userCode"></el-input>
              </div>
            </el-form-item>
          </dg-col>
        </div>
      </dg-row>
      <dg-row>
        <dg-col :span="24">
          <el-form-item label="权限有效期：" prop="permissionValidType">
            <div v-if="isDetail">
              <span v-if="sizeForm.permissionValidType == '01'"
                >{{ sizeForm.startTime | dateFormatter }} 至 {{ sizeForm.endTime | dateFormatter }}</span
              >
              <span v-else>长期</span>
            </div>
            <div v-else>
              <dg-row>
                <dg-col :span="6">
                  <dg-radio
                    v-model="sizeForm.permissionValidType"
                    :label="radio.code"
                    call-off
                    v-for="radio in shortBtns"
                    :key="radio.code"
                    >{{ radio.text }}</dg-radio
                  >
                </dg-col>
                <dg-col :span="10">
                  <dg-date-picker
                    :start-value.sync="sizeForm.startTime"
                    :end-value.sync="sizeForm.endTime"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    :default-time="['00:00:00', '23:59:59']"
                    v-show="sizeForm.permissionValidType !== '02'"
                    :picker-options="pickerOptions"
                    clearable
                    :unlink-panels="true"
                  >
                  </dg-date-picker>
                </dg-col>
              </dg-row>
            </div>
          </el-form-item>
        </dg-col>
      </dg-row>
      <!-- v1.0.0不实现 -->
      <!-- <dg-row>
                <dg-col :span="12">
                    <el-form-item label="附件：">
                        <div v-if="!isDetail">
                            <p v-for="item in sizeForm.fj" :key="item.url">
                                <dg-button type="text" class="dg-color-text-65" @click="handleDownLoad(item)"
                                    ><i class="icon iconfont iconl-link dg-color-text-25"></i>
                                    {{ item.name }}</dg-button
                                >
                            </p>
                        </div>
                        <div v-else>
                            <dg-upload
                                ref="upload"
                                list-type="button"
                                action="http://192.168.10.14:7300/mock/5d0a8c81e711b09fc48914c0/example/upload"
                                :on-remove="handleFileRemove"
                                :before-remove="beforeFileRemove"
                                multiple
                                :on-exceed="handleFileExceed"
                                :on-success="handleFileSuccess"
                                size="5m"
                                v-model="sizeForm.fj"
                            >
                            </dg-upload>
                        </div>
                    </el-form-item>
                </dg-col>
            </dg-row> -->
    </el-form>
    <div v-footer>
      <dg-button @click="handleCancel">取消</dg-button>
      <dg-button type="primary" @click="handleSave">保存</dg-button>
      <dg-button type="primary" @click="handleSubmit">提交</dg-button>
    </div>
  </div>
</template>

<script>
import { checkPhone } from '@/utils/regular';
import appFuncForm from './app-func-form.vue';
import serviceSourceForm from './service-source-form.vue';
import dataSourceForm from './data-source-form.vue';
import moment from 'moment';
import { savePermissionApply } from '@/api/permission-selfhelp-manage';

export default {
  name: 'FormItem',
  // 接收父页面传过来的属性
  props: {
    id: [String],
    type: {
      type: String
    }
  },
  // 页面数据绑定
  data() {
    const checkPhoneValid = (rule, val, callback) => {
      if (!val) {
        return callback(new Error('请输入手机号码'));
      }
      if (val && !checkPhone(val)) {
        return callback(new Error('请输入正确格式的手机号码'));
      }
      callback();
    };
    return {
      sizeForm: {},
      approveComponent: 'appFuncForm',
      applyType: [
        {
          label: '应用功能访问权限',
          value: '0'
        },
        {
          label: '服务资源访问权限',
          value: '1'
        },
        {
          label: '数据资源访问权限',
          value: '2'
        }
      ],
      processNameType: [
        {
          label: '应用功能访问权限申请',
          value: '0'
        },
        {
          label: '服务资源访问权限申请',
          value: '1'
        }
      ],
      rules: {
        flowContent: { required: true, message: '请选择审批内容', trigger: 'blur' },
        applyType: { required: true, message: '请选择审批类型', trigger: 'blur' },
        processName: { required: true, message: '请输入流程名称', trigger: 'blur' },
        applyReason: [{ required: true, message: '请输入申请理由', trigger: 'blur' }],
        applicantPhoneNo: [
          { required: true, message: '请输入申请人电话号码', trigger: 'blur' },
          { validator: checkPhoneValid, trigger: 'blur' }
        ],
        permissionValidType: { required: true, message: '请选择有效期类型', trigger: 'change' },
        applyId: [{ required: true, message: '请选择应用方', trigger: 'blur' }], // 应用方
        userName: [{ required: true, message: '请输入人员名称', trigger: 'blur' }],
        userType: [{ required: true, message: '请选择人员类型', trigger: 'blur' }],
        userCode: [{ required: true, message: '请输入人员编号', trigger: 'blur' }]
      },
      shortBtns: [
        {
          text: '自定义',
          time: '01',
          code: '01'
        },
        {
          text: '长期',
          time: '02',
          code: '02'
        }
      ],
      pickerOptions: {
        disabledDate(currentDate) {
          return currentDate.getTime() < Date.now() - 8.64e7;
        }
      },
      applySelectKeys: []
    };
  },
  components: {},
  computed: {
    isDetail() {
      return this.type == 'detail';
    }
  },
  watch: {
    'sizeForm.processName': {
      handler(val) {
        if (val) {
          this.sizeForm.applyTitle =
            this.processNameType.find((item) => item.value == val).label +
            '-' +
            this.sizeForm.applicantName +
            '-' +
            moment().format('YYYY-MM-DD');
          this.sizeForm.businessCode = val;
        }
      }
    },
    'sizeForm.applyType': {
      handler(val) {
        this.sizeForm.applicantId = val;
      }
    }
  },
  methods: {
    // 改变流程名称
    handleChangeProcessName() {},
    // 取消
    handleCancel() {
      this.$emit.close();
    },
    // 保存
    handleSave() {
      this.sizeForm.operateType = '1';
      this.save();
    },
    // 提交
    handleSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if ( !this.sizeForm.startTime && !this.sizeForm.endTime) {
            this.$message.warning("请选择开始时间和结束时间!");
            return;
          }
          this.sizeForm.operateType = '2';
          this.save();
        }
      });
    },
    save() {
      const { resourceInfos, applyId, userType, userName, userCode, ...otherInfo } = this.sizeForm;
      const params = {
        resourceInfos,
        workFlow: otherInfo
      };
      savePermissionApply(params).then((res) => {
        if (this.sizeForm.operateType == '2') {
          this.$message.success('提交成功！');
        } else {
          this.$message.success('保存成功！');
        }
        this.$emit('success');
      });
    },
    // 选择
    handleChoice() {
      const vm = this;
      const applyType = vm.sizeForm.applyType;
      // 审批内容选择
      let component;
      if (applyType == '0') {
        component = appFuncForm;
      } else if (applyType == '1') {
        component = serviceSourceForm;
      } else {
        component = dataSourceForm;
      }

      const layer = this.$dgLayer({
        title: '选择资源',
        shadow: [0.4, '#fff'],
        props: {
          selectKeys: this.applySelectKeys
        },
        content: component,
        area: ['1200px', '700px'],
        on: {
          success(approveContent, selectKeys, resourceInfos = []) {
            vm.sizeForm.resourceInfos = resourceInfos;
            vm.applySelectKeys = selectKeys;
            vm.sizeForm.flowContent = vm.sizeForm.applicantName + '申请访问资源：' + approveContent;
            layer.close(layer.dialogIndex);
          },
          close() {
            layer.close(layer.dialogIndex);
          }
        }
      });
    },
    // 切换审批类型
    handleChangeApproveType(val) {
      this.sizeForm.flowContent = '';
      this.sizeForm.resourceInfoDTO = [];
      if (val == '0') {
        this.approveComponent = 'appFuncForm';
      }
    },
    /**
     * 下载附件
     */
    handleDownLoad(item) {},

    /**
     * 文件列表移除文件时,sizebool false为文件超出
     */
    handleFileRemove(file, fileList) {
      console.log(file, fileList);
    },

    /**
     * 文件上传成功
     */
    handleFileSuccess(response, file, fileList) {
      console.log(response, file, fileList);
    },

    /**
     * 文件超出个数限制时
     */
    handleFileExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },

    /**
     * 删除文件之前，参数为上传的文件和文件列表，若返回 false 或者返回 Promise 且被 reject，则停止删除。
     */
    beforeFileRemove(file, fileList, sizeBool) {
      if (sizeBool === false) {
        return;
      }
      return this.$confirm(`确定移除 ${file.name}？`);
    }
  },
  created() {
    const { name, idcard, securityOrg, securityOrgName, mobile, id } = this.$store.getters.user;
    if (!this.id) {
      this.sizeForm = {
        // 流程标题
        applyTitle: '',
        applicantId: '0', // id
        applicantIdcard: idcard, // 申请人身份证号
        applicantName: name, // 申请人姓名
        applicantOrgCode: securityOrg, // 申请人机构代码
        applicantOrgName: securityOrgName, //申请人机构名称
        applicantPhoneNo: mobile, // 申请人号码
        flowContent: '', // 审核内容
        applyReason: '', // 申请原因
        businessCode: '', // 前端无用
        operateType: '', // 1--保存  2--提交
        applyType: '0',
        processName: '',
        permissionValidType: '02',
        startTime: '',
        endTime: '',
        resourceInfos: [],
        applyId: '', // 应用方
        userType: '',
        userName: '',
        userCode: ''
      };
    }
  },
  mounted() {}
};
</script>
<style scoped lang="scss">
// @import './index.scss';
</style>
