<template>
  <ele-modal
    :visible="visible"
    :title="title"
    width="65%"
    :destroy-on-close="true"
    @update:visible="updateVisible"
    :maxable="true"
    append-to-body
  >
    <div class="switch" v-if="title == '详情'">
      <div class="switch_left">
        <ul>
          <li
            v-for="item in tabOptions"
            :key="item.key"
            :class="{ active: activeComp == item.key }"
            @click="activeComp = item.key"
          >
            {{ item.name }}
          </li>
        </ul>
      </div>
    </div>
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      size="small"
      v-show="activeComp == 'main'"
      style="margin-top: 15px"
    >
      <!-- 第一行：印章编码 + 印章名称 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="印章编码" prop="code">
            <el-input
              v-model="form.code"
              placeholder="系统自动生成，唯一码"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="印章名称" prop="name" required>
            <el-input
              v-model="form.name"
              placeholder="请输入"
              :disabled="title == '详情' || title == '变更'"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行：印章类型 + 印章编号 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="印章类型" prop="sealType" required>
            <DictSelection
              dictName="印章类型"
              clearable
              filterable
              v-model="form.sealType"
              :isProhibit="title == '详情' || title == '变更'"
            >
            </DictSelection>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="印章编号" prop="sealNumber">
            <el-input
              v-model="form.sealNumber"
              placeholder="请输入"
              :disabled="title == '详情' || title == '变更'"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行：印章持有人 + 版本 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="印章持有人" prop="sealHolderName">
            <el-input
              :maxlength="20"
              v-model="form.sealHolderName"
              @click.native="setUsers"
              placeholder="选择人员"
              :disabled="title == '详情'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="版本" prop="version" required>
            <el-input
              v-model="form.version"
              placeholder="请输入"
              :disabled="title == '详情'"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第四行：是否长期有效 + 状态 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="是否长期有效" prop="isLongTerm" required>
            <el-radio-group
              v-model="form.isLongTerm"
              :disabled="title == '详情'"
            >
              <el-radio :label="1">长期</el-radio>
              <el-radio :label="0">非长期</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="状态" prop="status" required>
            <el-switch
              v-model="form.status"
              :disabled="title == '详情'"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
        </el-col> -->
      </el-row>

      <!-- 非长期时显示有效期 -->
      <el-row :gutter="20" v-if="form.isLongTerm == '0'">
        <el-col :span="12">
          <el-form-item label="有效期开始日期" prop="validStartDate">
            <el-date-picker
              v-model="form.validStartDate"
              :disabled="title == '详情'"
              type="date"
              value-format="yyyy-MM-dd"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="有效期结束日期" prop="validEndDate">
            <el-date-picker
              v-model="form.validEndDate"
              type="date"
              value-format="yyyy-MM-dd"
              :disabled="title == '详情'"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 印章图片上传 -->
      <el-row>
        <el-col :span="24">
          <el-form-item label="印章图片" prop="imgUrl" required>
            <div class="upload-container">
              <WithView
                :assetName="''"
                :disabled="title == '详情'"
                v-model="form.imgUrl"
                style="max-height: 370px"
              ></WithView>
              <div class="upload-tips">
                <p>上传要求：</p>
                <p>1、图像样式必须与实物印章的印模规制保持一致。</p>
                <p>2、印模必须清晰、完整、无断裂、无拖影</p>
              </div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template slot="footer">
      <el-button
        type="primary"
        size="small"
        @click="handleSave"
        v-if="title != '详情'"
        >保存</el-button
      >
      <el-button
        type="primary"
        size="small"
        @click="handleSave('sub')"
        v-if="title != '详情'"
        >保存并提交</el-button
      >
      <el-button size="small" @click="handleCancel">取消</el-button>
    </template>
    <addUser ref="addREf" @changeParent="userBk"></addUser>
    <bpmDetail
      v-if="activeComp == 'bpm' && form.processInstanceId"
      :id="form.processInstanceId"
    ></bpmDetail>
    <list v-if="activeComp == 'list' && form.id" :sealId="form.id"></list>
    <process-submit-dialog
      :isNotNeedProcess="false"
      :processSubmitDialogFlag.sync="processSubmitDialogFlag"
      v-if="processSubmitDialogFlag"
      ref="processSubmitDialogRef"
      @reload="reload"
    ></process-submit-dialog>
  </ele-modal>
</template>

<script>
  import {
    addSeal,
    changeSeal,
    updateSeal,
    getSealById
  } from '@/api/sealManagement';
  import addUser from '@/views/rulesManagement/earlyWarningRules/components/user-select/user-select.vue';
  import WithView from '@/components/upload/WithViewNew.vue';
  import bpmDetail from '@/views/bpm/processInstance/businessDetail.vue';
  import list from './list.vue';
  import processSubmitDialog from '@/components/processSubmitDialog/processSubmitDialog.vue';

  const defaultForm = {
    code: '',
    imgUrl: '',
    isLongTerm: 1,
    name: '',
    remark: '',
    sealHolderId: '',
    sealHolderName: '',
    sealNumber: '',
    sealType: 'legal_effect',
    sealTypeName: '',
    status: 0,
    processInstanceId: '',
    validEndDate: '',
    validStartDate: '',
    version: ''
  };

  export default {
    components: { addUser, WithView, bpmDetail, list, processSubmitDialog },
    name: 'SealDialog',
    data() {
      return {
        activeComp: 'main',
        tabOptions: [
          { key: 'main', name: '详情' },
          { key: 'bpm', name: '流程详情' },
          { key: 'list', name: '使用记录' }
        ],
        processSubmitDialogFlag: false,
        visible: false,
        title: '新增',
        sealTypeList: [
          {
            label: '法律效力章',
            value: '1'
          },
          {
            label: '财务专用章',
            value: '2'
          },
          {
            label: '业务专用章',
            value: '3'
          },
          {
            label: '内部管理章',
            value: '4'
          }
        ],
        form: {
          ...defaultForm
        },
        rules: {
          name: [
            { required: true, message: '请输入印章名称', trigger: 'blur' }
          ],
          sealType: [
            { required: true, message: '请选择印章类型', trigger: 'change' }
          ],
          version: [{ required: true, message: '请输入版本', trigger: 'blur' }],
          isLongTerm: [
            { required: true, message: '请选择是否长期有效', trigger: 'change' }
          ],
          status: [
            { required: true, message: '请选择状态', trigger: 'change' }
          ],
          sealHolderId: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          imgUrl: [
            { required: true, message: '请上传印章图片', trigger: 'change' }
          ],
          validStartDate: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          validEndDate: [
            { required: true, message: '请选择', trigger: 'change' }
          ]
        }
      };
    },
    methods: {
      open(row, type = 'add') {
        this.activeComp = 'main';
        console.log(type, 'type');

        if (row && (type == 'edit' || type == 'modify' || type == 'view')) {
          getSealById(row.id).then((res) => {
            this.form = res;
            if (type == 'modify') {
              this.form.parentId = row.id;
            }
          });
          this.title =
            type == 'edit' ? '修改' : type == 'modify' ? '变更' : '详情';
        } else {
          this.title = '新增';
          this.resetForm();
        }
        this.visible = true;
      },
      setUsers() {
        this.$refs.addREf.open();
      },
      updateVisible(val) {
        this.visible = val;
        if (!val) {
          this.resetForm();
        }
      },
      userBk(data) {
        console.log(data, 'data');
        this.form.sealHolderId = data.map((item) => item.id).toString();
        this.form.sealHolderName = data.map((item) => item.name).toString();
      },
      resetForm() {
        this.form = {
          ...defaultForm
        };
        this.$nextTick(() => {
          this.$refs.formRef && this.$refs.formRef.clearValidate();
        });
      },
      // 图片上传
      handleImageChange(file) {
        const isJPG = file.raw.type === 'image/jpeg';
        const isPNG = file.raw.type === 'image/png';
        const isBMP = file.raw.type === 'image/bmp';
        const isLt10M = file.raw.size / 1024 / 1024 < 10;

        if (!isJPG && !isPNG && !isBMP) {
          this.$message.error('上传图片只能是 JPG、PNG、BMP 格式!');
          return false;
        }
        if (!isLt10M) {
          this.$message.error('上传图片大小不能超过 10MB!');
          return false;
        }

        this.form.sealImage = file.raw;
        this.form.sealImageUrl = URL.createObjectURL(file.raw);
      },

      // 保存
      async handleSave(type) {
        this.$refs.formRef.validate(async (valid) => {
          if (valid) {
            let api =
              this.title === '新增'
                ? addSeal
                : this.title === '变更'
                ? changeSeal
                : updateSeal;
            try {
              api(this.form).then((res) => {
                if (type === 'sub') {
                  this.sub(this.title == '修改' ? this.form.id : res);
                  return;
                }
                this.$message.success('保存成功');
                this.$emit('reload');
                this.visible = false;
              });
            } catch (error) {
              this.$message.error(error.message || '保存失败');
            }
          }
        });
      },
      async sub(res) {
        let data = await getSealById(res);
        this.processSubmitDialogFlag = true;
        this.$nextTick(() => {
          let params = {
            businessId: data.id,
            businessKey: 'main_seal_management_approval',
            formCreateUserId: data.createUserId,
            variables: {
              businessCode: data.code,
              businessName: data.name,
              businessType: '印章审核'
            }
          };

          this.$refs.processSubmitDialogRef.init(params);
        });
      },
      reload() {
        this.$emit('reload');
        this.visible = false;
      },
      // 取消
      handleCancel() {
        this.visible = false;
      }
    }
  };
</script>

<style scoped>
  .upload-container {
    display: flex;
    align-items: flex-start;
    gap: 20px;
  }

  .seal-uploader {
    width: 200px;
    height: 200px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    background-color: #f5f7fa;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .seal-uploader:hover {
    border-color: #409eff;
  }

  .uploader-placeholder {
    text-align: center;
    color: #8c939d;
  }

  .uploader-placeholder .el-icon-picture-outline {
    font-size: 48px;
    margin-bottom: 10px;
  }

  .upload-text {
    display: flex;
    gap: 10px;
    justify-content: center;
  }

  .delete-btn {
    color: #f56c6c;
  }

  .seal-image {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }

  .upload-tips {
    flex: 1;
    font-size: 12px;
    color: #606266;
    line-height: 1.8;
  }

  .upload-tips p {
    margin: 0;
    padding: 0;
  }

  .upload-tips p:first-child {
    font-weight: bold;
    margin-bottom: 5px;
  }
</style>
