<!--
@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"
      v-if="show"
    >
      <dg-row>
        <dg-col :span="12">
          <el-form-item label="审批类型：" prop="applyType">
            <div v-if="isDetail">
              <div class="u-detail__text" v-translate="{ enum: 'SelfAuthApplyTypeEnum' }">
                {{ sizeForm.applyType }}
              </div>
            </div>
            <div v-else>
              <dg-select
                enum="SelfAuthApplyTypeEnum"
                v-model="sizeForm.applyType"
                :disabled="type == 'edit'"
                @change="handleChangeApplyType"
              ></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>
              <el-input v-model="sizeForm.processName" :disabled="true"></el-input>
            </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="applicantOrdNo">
            <div>{{ sizeForm.applicantOrdNo }}</div>
          </el-form-item>
        </dg-col>
        <dg-col :span="12">
          <!-- 流程名称+申请人姓名+日期 -->
          <el-form-item label="审批单标题：" prop="flowTitle">
            <div v-if="isDetail">{{ sizeForm.flowTitle }}</div>
            <div v-else>
              <el-input v-model="sizeForm.flowTitle" :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="isDetail">
          <el-form-item label="创建时间：">
            {{ sizeForm.createTime }} 
          </el-form-item>
        </dg-col>
        <dg-col :span="12" v-if="sizeForm.applyType == 'SERVICE_AUTH'">
          <el-form-item label="应用方：" prop="applyId">
            <div v-if="isDetail">{{ sizeForm.applyId }}</div>
            <div v-else>
              <dg-select :data="appList" v-model="sizeForm.applyId"></dg-select>
            </div>
          </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 }" :value="flowContentStr" :disabled="true"></el-input>
              <dg-button style="margin-left: 10px" @click="handleChoice" v-if="sizeForm.applyType">选择</dg-button>
            </div>
            <div v-else>
              {{ flowContentStr }}
            </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 == 'DATA_AUTH'">
          <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>
      <div v-if="type !== 'detail'">
        <dg-button @click="handleCancel">取消</dg-button>
        <!-- <dg-button type="primary" @click="handleSave">保存</dg-button> -->
        <dg-button type="primary" @click="handleSubmit">提交</dg-button>
      </div>
    </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 * as Api from '@/api/permission-selfhelp-manage';

export default {
  name: 'FormItem',
  // 接收父页面传过来的属性
  props: {
    applyOrdNo: [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();
    };

    // 验证有效期间
    const checkPermissionValid = (rule, val, callback) => {
      if (val == '01') {
        if (!this.sizeForm.startTime && !this.sizeForm.endTime) {
          return callback(new Error('请选择开始时间和结束时间'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    return {
      sizeForm: {},
      approveComponent: 'appFuncForm',
      rules: {
        flowContent: { required: true, message: '请选择审批内容', trigger: 'change' },
        applyType: { required: true, message: '请选择审批类型', trigger: 'change' },
        flowTitle: { required: true, message: '请输入审批单标题', trigger: 'change' },
        applicantName: { required: true, message: '请输入申请人姓名', trigger: 'change' },
        applicantIdcard: { required: true, message: '请输入申请人身份证号码', trigger: 'change' },
        applicantOrgCode: { required: true, message: '请输入申请人单位代码', trigger: 'change' },
        applicantOrgName: { required: true, message: '请输入申请人单位名称', trigger: 'change' },
        processName: { required: true, message: '请输入流程名称', trigger: 'change' },
        applyReason: [{ required: true, message: '请输入申请理由', trigger: 'change' }],
        applicantPhoneNo: [
          { required: true, message: '请输入申请人电话号码', trigger: 'change' },
          { validator: checkPhoneValid, trigger: 'change' }
        ],
        permissionValidType: { required: true, validator: checkPermissionValid, trigger: 'change' },
        applyId: [{ required: true, message: '请选择应用方', trigger: 'change' }], // 应用方
        userName: [{ required: true, message: '请输入人员名称', trigger: 'change' }],
        userType: [{ required: true, message: '请选择人员类型', trigger: 'change' }],
        userCode: [{ required: true, message: '请输入人员编号', trigger: 'change' }]
      },
      shortBtns: [
        {
          text: '自定义',
          time: '01',
          code: '01'
        },
        {
          text: '长期',
          time: '02',
          code: '02'
        }
      ],
      pickerOptions: {
        disabledDate(currentDate) {
          return currentDate.getTime() < Date.now() - 8.64e7;
        }
      },
      applySelectKeys: [],
      appList: [
        {
          value: '测试应用',
          label: '测试应用'
        }
      ],
      applyContentCom: appFuncForm,
      show: false,
      applyContentOperateObj: {
        'function-auth-apply': {
          applyText: '申请访问资源：',
          cancelText: '申请撤销资源：'
        },
        'service-auth-apply': {
          applyText: '申请服务：',
          cancelText: '申请撤销服务：'
        }
      },
      needFilter: true
    };
  },
  components: {},
  computed: {
    isDetail() {
      return this.type == 'detail';
    },
    flowContentStr() {
      let str = '';
      if (this.sizeForm.flowContent) {
        const { visitorName, visitResourceName, cancelResourceName } = JSON.parse(this.sizeForm.flowContent);
        const { applyText, cancelText } = this.applyContentOperateObj[this.sizeForm.businessCode] || {};
        const applyContent = visitResourceName ? `${applyText}${visitResourceName}。\n` : '';
        const cancelContent = cancelResourceName ? `${cancelText}${cancelResourceName}。` : '';
        str = `${visitorName}${applyContent}${cancelContent}`;
      }
      return str;
    }
  },
  watch: {
    'sizeForm.applyType': {
      handler(val) {
        let component;
        if (val == 'DATA_AUTH') {
          component = dataSourceForm;
        } else if (val == 'SERVICE_AUTH') {
          component = serviceSourceForm;
        } else {
          component = appFuncForm;
        }
        this.applyContentCom = component;
      }
    }
  },
  methods: {
    // 获取流程名称
    getProcessName(val) {
      Api.getFlowDefine(val).then((res) => {
        const { content, result, msg } = res.data;
        if (result == '200') {
          this.sizeForm.processName = content.processName;
          this.sizeForm.businessCode = content.businessCode;
          this.sizeForm.processType = content.processTypeCode;
          // 审批单标题 = 流程名称 + 申请人姓名 + 日期
          this.sizeForm.flowTitle = `${content.processName}-${this.sizeForm.applicantName}-${moment().format(
            'YYYY-MM-DD'
          )}`;
        } else {
          this.$message.warning(msg);
        }
      });
    },
    // 切换审批类型,清空审批内容
    handleChangeApplyType(val) {
      this.sizeForm.flowContent = '';
      this.sizeForm.resourceInfos = [];
      this.applySelectKeys = [];
      this.getProcessName(val);
    },
    // 取消/关闭
    handleCancel() {
      this.$emit('close');
    },
    // 保存
    handleSave() {
      if (this.sizeForm.applyType !== 'APP_FUN_AUTH') return;
      this.sizeForm.operateType = '1';
      this.save();
    },
    // 提交
    handleSubmit() {
      if (this.sizeForm.applyType == 'APP_FUN_AUTH' || !this.sizeForm.applyType) {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            this.sizeForm.operateType = '2';
            this.save();
          }
        });
      }
    },
    save() {
      const { resourceInfos, applyId, userType, userName, userCode, ...otherInfo } = this.sizeForm;
      let params = {
        resourceInfos
      };
      let api = '';

      if (this.type == 'add') {
        params['workFlow'] = otherInfo;
        api = 'savePermissionApply';
      } else {
        const { permissionValidType, operateType, applicantPhoneNo, applyReason, startTime, endTime, flowContent } =
          this.sizeForm;
        // 只选可编辑的字段
        params = {
          resourceInfos,
          permissionValidType,
          operateType,
          applicantPhoneNo,
          applyReason,
          startTime,
          endTime,
          flowContent,
          applyOrdNo: this.applyOrdNo
        };
        api = 'updateApply';
      }

      Api[api](params).then((res) => {
        if (this.sizeForm.operateType == '2') {
          this.$message.success('提交成功！');
        } else {
          this.$message.success('保存成功！');
        }
        this.$emit('success');
      });
    },
    // 选择
    handleChoice() {
      const vm = this;
      // const keys = [...this.applySelectKeys, ...this.sizeForm.resourceInfos.map((item) => item.funId)];
      const layer = this.$dgLayer({
        title: '选择资源',
        shadow: [0.4, '#fff'],
        props: {
          selectKeys: this.applySelectKeys,
          needFilter: this.needFilter,
          type: this.type
        },
        content: this.applyContentCom,
        area: ['1200px', '700px'],
        on: {
          success(visitResourceName, cancelResourceName, selectKeys, resourceInfos = []) {
            vm.sizeForm.resourceInfos = resourceInfos;
            vm.applySelectKeys = selectKeys;
            const visitorName =
              vm.sizeForm.applyType !== 'SERVICE_AUTH' ? vm.sizeForm.applicantName : vm.sizeForm.applyId;
            const resourceObj = { visitorName, visitResourceName, cancelResourceName };
            vm.sizeForm.flowContent = JSON.stringify(resourceObj);
            vm.needFilter = false;
            layer.close(layer.dialogIndex);
          },
          close() {
            layer.close(layer.dialogIndex);
          }
        }
      });
    },
    /**
     * 下载附件
     */
    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}？`);
    },
    getDetail() {
      const params = {
        applyOrdNo: this.applyOrdNo,
        needFlowInfo: true
      };
      Api.applyDetail(params).then((res) => {
        const { workFlow, resourceInfos, ...otherInfo } = res.data.content;
        this.sizeForm = {
          ...workFlow,
          resourceInfos,
          ...otherInfo
        };
        this.applySelectKeys = this.sizeForm.resourceInfos.map((item) => item.funId);
        this.show = true;
      });
    }
  },
  created() {
    const { name, idcard, securityOrgs, securityOrgName, mobile, id } = this.$store.getters.user;
    if (!this.applyOrdNo) {
      this.sizeForm = {
        flowTitle: '',
        applicantIdcard: idcard,
        applicantName: name,
        applicantOrgCode: securityOrgs[0],
        applicantOrgName: securityOrgName,
        applicantPhoneNo: mobile,
        flowContent: '',
        applyReason: '',
        businessCode: '',
        processType: '',
        operateType: '', // 1--保存  2--提交
        applyType: '',
        processName: '',
        permissionValidType: '02',
        startTime: '',
        endTime: '',
        resourceInfos: [],
        applyId: '', // 应用方
        userType: '',
        userName: '',
        userCode: ''
      };
      this.show = true;
    } else {
      this.getDetail();
      if (this.type == 'detail') {
        this.rules = {};
      }
    }
  },
  mounted() {}
};
</script>
<style scoped lang="scss">
// @import './index.scss';
</style>
