<!--
@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'"
                placeholder="请选择审批类型"
                @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" placeholder="请输入流程名称" :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" placeholder="请输入审批单标题"></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" placeholder="请输入申请人手机号码"></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"
                placeholder="请选择审批内容"
              ></el-input>
              <dg-button style="margin-left: 10px" @click="handleChoice" v-if="sizeForm.applyType && !this.repeatApply"
                >选择</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 }"
                placeholder="请输入申请理由"
              ></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
                    v-model="dateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd"
                    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>
    <!-- 重复申请提示框 -->
    <dg-dialog title="提示" :visible.sync="visible" width="450px" :modal="false">
      <p class="repeatContent">
        您存在待审批的审批单，审批单号：
        <span @click="handleOpenDetail">
          {{ repeatApply }}
        </span>
        ，无法申请，请等待审批后再进行资源申请。
      </p>
      <span slot="footer" class="dialog-footer">
        <dg-button @click="visible = false">关闭</dg-button>
      </span>
    </dg-dialog>
  </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.dateRange) {
          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'
        }
      ],
      dateRange: '',
      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,
      visible: false,
      repeatApply: ''
    };
  },
  components: {},
  computed: {
    isDetail() {
      return this.type == 'detail';
    },
    flowContentStr() {
      let str = '';
      if (this.sizeForm.flowContent) {
        const { visitorName, visitResourceName, removeVisitResourceNames } = JSON.parse(this.sizeForm.flowContent);
        const { applyText, cancelText } = this.applyContentOperateObj[this.sizeForm.businessCode] || {};
        const applyContent = visitResourceName ? `${applyText}${visitResourceName}。\n` : '';
        const cancelContent = removeVisitResourceNames ? `${cancelText}${removeVisitResourceNames}。` : '';
        str = `${visitorName}${applyContent}${cancelContent}`;
      }
      return str;
    }
  },
  watch: {
    'sizeForm.applyType': {
      handler(val) {
        if (val) {
          let component;
          if (val == 'DATA_AUTH') {
            component = dataSourceForm;
          } else if (val == 'SERVICE_AUTH') {
            component = serviceSourceForm;
          } else {
            component = appFuncForm;
          }
          this.applyContentCom = component;
        }
      }
    }
  },
  methods: {
    handleOpenDetail() {
      const layer = this.$dgLayer({
        title: '详情',
        props: {
          applyOrdNo: this.repeatApply,
          type: 'detail'
        },
        content: require('./detail.vue'),
        area: ['1280px', '900px'],
        on: {
          success(params) {
            layer.close(layer.dialogIndex);
          },
          close() {
            layer.close(layer.dialogIndex);
          }
        }
      });
    },
    // 获取流程名称
    getProcessName(val) {
      // 暂时处理： 服务和数据资源暂不开放，直接提示‘功能设计中，敬请期待！’
      if (val == 'APP_FUN_AUTH') {
        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);
          }
        });
      } else {
        this.$message.warning('功能设计中，敬请期待！');
      }
    },
    // 切换审批类型,判断是否存在未审批的单,清空审批内容
    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';
            Api.rediListCheck(this.sizeForm.resourceInfos).then((res) => {
              const { result, content, msg } = res.data;
              if (result == '200') {
                if (content === true) {
                  // 说明存在风险
                  this.$dgConfirm(`您申请的内容命中功能红名单风险，请确定是否继续申请？`, '风险提示', {}).then(
                    () => {
                      this.save();
                    }
                  );
                } else {
                  // 没有命中直接保存
                  this.save();
                }
              } else {
                this.$message.warning(msg);
              }
            });
          }
        });
      }
    },
    save() {
      const { resourceInfos, delResourceInfos, applyId, userType, userName, userCode, ...otherInfo } = this.sizeForm;
      let params = {
        resourceInfos,
        delResourceInfos
      };
      let api = '';
      if (this.sizeForm.permissionValidType == '01') {
        this.sizeForm.startTime = this.dateRange[0];
        this.sizeForm.endTime = this.dateRange[1];
      }
      if (this.type == 'add') {
        params['workFlow'] = otherInfo;
        api = 'savePermissionApply';
      } else {
        const {
          permissionValidType,
          operateType,
          applicantPhoneNo,
          applyReason,
          startTime,
          endTime,
          flowContent,
          delResourceInfos
        } = this.sizeForm;
        // 只选可编辑的字段
        params = {
          resourceInfos,
          delResourceInfos,
          permissionValidType,
          operateType,
          applicantPhoneNo,
          applyReason,
          startTime,
          endTime,
          flowContent,
          applyOrdNo: this.applyOrdNo
        };
        api = 'updateApply';
      }

      Api[api](params).then((res) => {
        const { result, msg } = res.data;
        if (result == '200') {
          if (this.sizeForm.operateType == '2') {
            this.$message.success('提交成功！');
          } else {
            this.$message.success('保存成功！');
          }
          this.$emit('success');
        } else {
          this.$message.error(msg);
        }
      });
    },
    // 选择
    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,
          applicantOrdNo: this.applyOrdNo
        },
        content: this.applyContentCom,
        area: ['1280px', '700px'],
        on: {
          success(visitResourceName, cancelResourceName, selectKeys, resourceInfos = [], delResourceInfos = []) {
            vm.sizeForm.resourceInfos = resourceInfos;
            vm.sizeForm.delResourceInfos = delResourceInfos;
            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, existResourceInfos, delResourceInfos, ...otherInfo } = res.data.content;
        this.sizeForm = {
          ...workFlow,
          resourceInfos,
          delResourceInfos,
          ...otherInfo
        };
        if (this.sizeForm.permissionValidType == '01') {
          this.dateRange = [this.sizeForm.startTime, this.sizeForm.endTime];
        }
        const delResourceInfoIds = delResourceInfos.map((item) => item.funId);
        // 默认选中节点 = 新增节点 + ( 已有节点 - 欲撤销节点 )
        this.applySelectKeys = [
          ...resourceInfos,
          ...existResourceInfos.filter((item) => !delResourceInfoIds.includes(item.funId))
        ].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: [],
        delResourceInfos: [],
        applyId: '', // 应用方
        userType: '',
        userName: '',
        userCode: ''
      };
      this.show = true;
    } else {
      this.getDetail();
      if (this.type == 'detail') {
        this.rules = {};
      }
    }
  },
  mounted() {}
};
</script>
<style scoped lang="scss">
.repeatContent {
  color: rgba(0, 0, 0, 0.85);
  span {
    color: #1890ff;
    cursor: pointer;
  }
}
</style>
