<template>
  <div>
    <div class="bigBox">
      <MOSTY.FromPage :title="props.title" @closeDialog="handleClose">
        <template #content>
          <div class="box-big">
            <div class="box-left">
              <el-form class="elfrom" ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="130px"
                :disabled="props.isdisabled" :inline="true" style="display: block;">
                <el-form-item label="责任书名称:" prop="zrsmc">
                  <el-input v-model="ruleForm.zrsmc" clearable style="width: 646px"></el-input>
                </el-form-item>
                <el-form-item label="责任书类型:" prop="lxs" style='width:100%;'>
                  <el-radio-group v-model="ruleForm.lxs" size="small" @change="changeLxs" :disabled='ISbj'>
                    <el-radio v-for="item in zslxlist" :value="item.value" :key="item.value" :label="item.value"
                      border>{{ item.label }}</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item :label="fqText + ':'" prop="fqdwid">
                  <el-input v-model="ruleForm.fqdwmc" readonly clearable style="width:260px" disabled>
                    <template #append>
                      <el-button disabled>选择</el-button>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item label="审批领导：" label-width="100px">
                  <el-input v-model="ruleForm.ldxm" readonly clearable style="width:260px" disabled>
                    <template #append>
                      <el-button @click="inputClick('02')">选择</el-button>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item :label="bqdText + ':'" prop="rydwid">
                  <el-input v-model="ruleForm.rydwmc" clearable readonly style="width:260px"
                    :placeholder="'请选择' + bqdText" :disabled='ISbj || bisab'>
                    <template #append>
                      <el-button @click="ChooesDdld">选择</el-button>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item label="签订人：" prop="ryxm" label-width="100px">
                  <el-input v-model="ruleForm.ryxm" placeholder="请选择签订人" readonly clearable style="width:260px"
                    :disabled='ISbj'>
                    <template #append>
                      <el-button @click="inputClick('01')">选择</el-button>
                    </template>
                  </el-input>
                </el-form-item>
              </el-form>
              <!-- 富文本 -->
              <div class="content" style="height:calc(100vh - 500px);">
                <vue-ueditor-wrap v-model="ruleForm.content" editor-id="editor" :config="editorConfig"
                  :editorDependencies="['ueditor.config.js', 'ueditor.all.js']" />
              </div>
            </div>
            <div class="box_right">
              <el-timeline style="max-width: 700px">
                <el-timeline-item v-for="(activity, index) in timelist" :key="index" :icon="activity.icon"
                  :type="activity.type" :color="activity.color" :size="activity.size" :hollow="activity.hollow">
                  <div class="time-top">
                    <div>
                      <span class="name-box">{{ activity.czrname }}</span>
                      <span class="lable-time yess" v-if='activity.czbz == "签订人签订"'>
                        {{ activity.czbz }}</span>
                      <span class="lable-time" v-if='activity.czbz != "签订人签订"' :class='activity.spyj ? "reds" : "gren"'>
                        {{ activity.czbz }}</span>
                    </div>
                    <div class="time-ri">
                      {{ activity.czsj }}
                    </div>
                  </div>
                  <el-card v-if="activity.spyj">
                    <p>{{ activity.spyj }}</p>
                  </el-card>
                </el-timeline-item>
              </el-timeline>
            </div>
          </div>

        </template>
        <template #footer>

          <el-button class="btn-clas" @click="showKKfile"
            v-if="props.title.indexOf('查看') != -1 || props.title.indexOf('修改') != -1">
            <el-icon>
              <View />
            </el-icon>
            <span>附件预览</span>
          </el-button>
          <el-button class="btn-clas" @click="downloadFile"
            v-if="props.title.indexOf('查看') != -1 || props.title.indexOf('修改') != -1">
            <el-icon>
              <Download />
            </el-icon>
            <span>附件下载</span>
          </el-button>
          <el-button type="primary" v-loading="loading" @click="handleSave(ruleFormRef, '0')" v-if="!props.isdisabled">
            <el-icon>
              <DocumentChecked />
            </el-icon>
            <span>保存</span>
          </el-button>
          <el-button type="primary" v-loading="loading" @click="handleSave(ruleFormRef, '1')" v-if="!props.isdisabled">
            <el-icon>
              <Position />
            </el-icon>
            <span>发起签订</span>
          </el-button>
          <el-button class="btn-clas" @click="handleClose">
            <el-icon>
              <DocumentDelete />
            </el-icon>
            <span>关闭</span>
          </el-button>
        </template>
      </MOSTY.FromPage>
      <!-- 选择部门 -->
      <Choosebm :showDdld="showDept" @closezzjg="closezzjg" :deptId="dwdeptId" :searchType="searchType"
        @listdata="getSonValues" :zzlx="zzlx" />
      <!-- 选择人员弹窗 -->
      <ChooseUser v-model="chooseUserVisible" :deptId="deptId" :Single="Single" :data="memberList" :zzlx="zzlx"
        :leaderid="leaderid" @choosedUsers="getSonValue" :key='keys'></ChooseUser>
      <!-- 预览 -->
      <div v-if="dialogVisible" class="dialog-box">
        <Kkfile :files="ruleForm.files" @changedialog="changedialog" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, defineProps, defineEmits, reactive, getCurrentInstance } from "vue";
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue";
import { getFile } from "@/utils/getFile.js";
import * as MOSTY from "@/components/MyComponents/index";
import Choosebm from "@/components/MyComponents/ChooseDept/index.vue";
import { getItem } from "@/utils/storage";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import { ElMessage } from "element-plus";
import Kkfile from "../../../../components/MyComponents/kkfile/index.vue";
const showDept = ref(false);
const { proxy } = getCurrentInstance();
const editorConfig = {
  serverUrl: '',
  UEDITOR_HOME_URL: '/UEditorPlus/'
}
const loading = ref(false);
const bisab = ref(false)
const Single = ref(true);
const dialogVisible = ref(false);
const ruleFormRef = ref();
const leaderid = ref("");
const searchType = ref("02");
const zzlx = ref("");
const chooseUserVisible = ref(false);
const ISbj = ref(false);
const deptId = ref(null)
const dwdeptId = ref(null)
const keys = ref(0)
const isdisabled = ref(false);
const zslxlist = ref([
  { value: "01", label: "单位对单位" },
  { value: "02", label: "单位对部门" },
  { value: "03", label: "部门对个人" },
  { value: "04", label: "主管领导对分管领导" }
]);
const emits = defineEmits(["changeAddVi"]);
//表单数据
const ruleForm = ref({});
const fqText = ref('发起单位')
const bqdText = ref('被签订单位')
const timelist = ref([
  {
    czbz: "新增责任书",
    czrname: getItem('USERNAME'),
    state: 0,
    xh: 0
  },
  // {
  //   czbz: "发起签订责任书",
  //   czrname: getItem('USERNAME'),
  //   state: 0,
  //   xh: 0
  // },
  {
    czbz: "领导审批责任书",
    czrname: ruleForm.value.fqdwmc ? ruleForm.value.fqdwmc : ruleForm.value.ldxm,
    state: 0,
    xh: 0
  }, {
    czbz: "签订人签订",
    czrname: ruleForm.value.rydwmc ? ruleForm.value.rydwmc : ruleForm.value.ryxm,
    state: 0,
    xh: 0
  },
  {
    czrname: '结束归档',
    state: '0',
    lx: 'end',
    size: 'large',
    hollow: true
  }
]);
const memberList = ref([]); //成员选择的id回显
//规则校验
const rules = reactive({
  zrsmc: [{ required: true, message: "责任书名称不能为空", trigger: "blur" }],
  lxs: [{ required: true, message: "责任书类型不能为空", trigger: "blur" }],
  ryxm: [{ required: true, message: "签订人不能为空", trigger: "blur" }],
  fqxgsmc: [{ trigger: "change", required: true, message: "发起单位不能为空" }],
  rydwid: [{ trigger: "change", required: true, message: "被签订单位不能为空" }],
  content: [{ trigger: "blur", required: true, message: "签订内容不能为空" }],
});
const props = defineProps({
  rowdata: {
    type: Object,
    default: {}
  },
  title: String,
  xqId: {
    type: String,
    default: ""
  },
  isdisabled: {
    type: Boolean,
    default: false
  }
});
// 初始化
onMounted(() => {

  resetfrom()
  ISbj.value = false
  ruleForm.value.signtype = '1'
  let dept = getItem("deptId");
  if (dept.orgBizType == "04") {
    if (dept.orgLevel.substring(0, 1) == '1' || dept.orgLevel.substring(0, 1) == '2') {
      ruleForm.value.lxs = "01";
    } else if (dept.orgLevel.substring(0, 1) == '3') {
      ruleForm.value.lxs = "02";
      zslxlist.value.splice(0, 1);
    } else {
      ruleForm.value.lxs = "03";
      zslxlist.value.splice(0, 3);
    }
  } else {
    ruleForm.value.lxs = "03";
    zslxlist.value.splice(0, 3);
  }
  if (props.xqId) {
    ISbj.value = true
    zrsXqData(props.xqId)
  } else {
    ISbj.value = false
    changeLxs()
  }
  setTimeout(function () {
    var ue = UE.getEditor('editor'); // 初始化UEditorPlus编辑器
    document.addEventListener('paste', function (e) {
      var clipboardData = e.clipboardData;
      var pastedData = clipboardData.getData('text'); // 获取剪贴板文本数据

      // 这里可以添加处理粘贴内容的逻辑，比如保留格式等

      ue.execCommand('insertHtml', pastedData); // 将获取的数据插入编辑器
      e.preventDefault(); // 阻止默认粘贴行为
    });

  }, 200);
});
// 附件下载
async function downloadFile() {
  let data = await getFile(ruleForm.value.files)
  fileAjax(data.innerUrl, function (xhr) {
    _downloadFile(xhr.response, data.originalName)
  }, {
    responseType: 'blob'
  })
}

function fileAjax(url, callback, options) {
  let xhr = new XMLHttpRequest()
  xhr.open('get', url, true)
  if (options.responseType) {
    xhr.responseType = options.responseType
  }
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
      callback(xhr)
    }
  }
  xhr.send()
}

function _downloadFile(content, filename) {
  window.URL = window.URL || window.webkitURL
  let a = document.createElement('a')
  let blob = new Blob([content])
  // 通过二进制文件创建url
  let url = window.URL.createObjectURL(blob)
  a.href = url
  a.download = filename
  a.click()
  // 销毁创建的url
  window.URL.revokeObjectURL(url)
}
// 责任书预览页面跳转
function showKKfile() {
  dialogVisible.value = true
}

// 切换责任书类型
const changeLxs = async (val) => {
  bisab.value = false
  let dept = getItem("deptId");
  let orgLevel = dept.orgLevel.substring(0, 1);
  dwdeptId.value = null
  searchType.value = null
  ruleForm.value.rydwid = '';
  ruleForm.value.rydwmc = null;
  ruleForm.value.ryid = null
  ruleForm.value.ryxm = null
  // 单位对单位
  if (ruleForm.value.lxs == '01') {
    dwdeptId.value = null
    if (orgLevel == '1') {
      searchType.value = "02";
    } else if (orgLevel == '2') {
      searchType.value = "03";
    }
    fqText.value = '发起单位'
    bqdText.value = '被签订单位'
    ruleForm.value.fqdwid = dept.ssdwid
    ruleForm.value.fqdwmc = dept.ssdwmc
    // 查询发起单位领导
    let ry = await getRy(ruleForm.value.fqdwid, null)
    ruleForm.value.ldid = ry.fqdwid
    ruleForm.value.ldxm = ry.fqdwname
    timelist.value[1].czrname = ruleForm.value.ldxm
  }
  if (ruleForm.value.lxs == '02') {
    searchType.value = "01";
    fqText.value = '发起单位'
    bqdText.value = '签订部门'
    dwdeptId.value = dept.ssdwid
    ruleForm.value.fqdwid = dept.ssdwid
    ruleForm.value.fqdwmc = dept.ssdwmc
    let ry = await getRy(ruleForm.value.fqdwid, null)
    ruleForm.value.ldid = ry.fqdwid
    ruleForm.value.ldxm = ry.fqdwname
    timelist.value[1].czrname = ruleForm.value.ldxm
  }
  if (ruleForm.value.lxs == "03") {
    fqText.value = '发起部门'
    bqdText.value = '签订部门'
    searchType.value = "01";
    bisab.value = true
    dwdeptId.value = dept.ssdwid
    ruleForm.value.fqdwid = dept.ssbmid
    ruleForm.value.fqdwmc = dept.ssbmmc
    ruleForm.value.rydwid = dept.ssbmid
    ruleForm.value.rydwmc = dept.ssbmmc
    let ry = await getRy(ruleForm.value.fqdwid, null)
    ruleForm.value.ldid = ry.fqdwid
    ruleForm.value.ldxm = ry.fqdwname
    let rys = await getRy(null, ruleForm.value.rydwid)
    ruleForm.value.ryid = rys.ryid
    ruleForm.value.ryxm = rys.ryxm
    timelist.value[1].czrname = ruleForm.value.ldxm
  }
  if (ruleForm.value.lxs == "04") {
    fqText.value = '发起单位'
    bqdText.value = '签订单位'
    searchType.value = '03'
    bisab.value = true
    dwdeptId.value = dept.ssdwid
    ruleForm.value.fqdwid = dept.ssdwid
    ruleForm.value.fqdwmc = dept.ssdwmc
    ruleForm.value.rydwid = dept.ssdwid
    ruleForm.value.rydwmc = dept.ssdwmc
    let ry = await getRy(ruleForm.value.rydwid, ruleForm.value.rydwid)
    ruleForm.value.ldid = ry.fqdwid
    ruleForm.value.ldxm = ry.fqdwname
    ruleForm.value.ryid = ry.bqddwid
    ruleForm.value.ryxm = ry.bqddwname
    timelist.value[1].czrname = ruleForm.value.ldxm
  }
}
// 查询审核人员活被签订人员
const getRy = async (fqdwid, bqddwbmid) => {
  let data = {
    zrslx: ruleForm.value.lxs,
    fqdwid: fqdwid,
    bqddwbmid: bqddwbmid
  }
  return new Promise(ok => {
    getApi(data, '/mosty-jcgl/securitychild/getFgldByZrslx').then((res) => {
      ok(res)
    })
  })
}

//重置
function resetfrom() {
  isdisabled.value = false;
  ruleForm.value = {}
  ruleFormRef.value.clearValidate();
  ruleFormRef.value.resetFields()
  ruleForm.value.fqxgsmc = getItem("deptId").ssdwmc;
  ruleForm.value.fqsgsid = getItem("deptId").ssdwid;
}
//关闭预览
function changedialog() {
  dialogVisible.value = false;
  UE.getEditor('editor').setShow()
}
//获取责任书详情
function zrsXqData(id) {
  getApi({ id }, '/mosty-jcgl/zrs/getZrsInfo').then((res) => {
    ruleForm.value = res;
    ruleForm.value.lxs = res.zrslx
    ruleForm.value.fqxgsmc = getItem("deptId").ssdwmc
    ruleForm.value.fqsgsid = getItem("deptId").ssdwid
    ruleForm.value.ldspyj = ruleForm.value.ldspyj ? ruleForm.value.ldspyj : '无'
    getZrsLc(props.xqId);
  })
}
//获取责任书进度
function getZrsLc(id) {
  timelist.value = []
  getApi({ id }, "/mosty-jcgl/zrsChild/getDetailByZrsid").then((res) => {
    timelist.value = res;
    timelist.value.forEach((item) => {
      item.size = 'large';
      item.hollow = true;
      if (item.state == '1') {
        item.color = '#0bbd87'
      }
      if (item.czbz == "签订人签订" && item.state == '1') {
        timelist.value.push({
          czrname: '结束归档',
          state: '1',
          color: '#0bbd87',
          lx: 'end',
          size: 'large',
          hollow: true
        })
      } else if (item.czbz == "签订人签订" && item.state == '0') {
        timelist.value.push({
          czrname: '结束归档',
          state: '0',
          lx: 'end',
          size: 'large',
          hollow: true
        })
      }

    });
  });
}

//选择部门
function ChooesDdld() {
  showDept.value = true;
}
//获取部门信息
const getSonValues = async (val) => {
  ruleForm.value.rydwid = val.id;
  ruleForm.value.rydwmc = val.orgName;
  deptId.value = val.id;
  if (ruleForm.value.lxs == '02') {
    let ry = await getRy(null, ruleForm.value.rydwid)
    ruleForm.value.ryid = ry.bqddwid
    ruleForm.value.ryxm = ry.bqddwname
    let ld = await getRy(ruleForm.value.rydwid, null)
    ruleForm.value.ldid = ld.fqdwid
    ruleForm.value.ldxm = ld.fqdwname
    timelist.value[2].czrname = ruleForm.value.ryxm
  } else {
    let ry = await getRy(null, ruleForm.value.rydwid)
    ruleForm.value.ryid = ry.bqddwid
    ruleForm.value.ryxm = ry.bqddwname
    timelist.value[2].czrname = ry.bqddwname

  }

}
//关闭弹窗
const closezzjg = (val) => {
  showDept.value = val;
};

// 选择人员
function inputClick(val) {
  zzlx.value = val;
  deptId.value = null
  leaderid.value = null
  if (val == "01") {
    Single.value = true
    deptId.value = ruleForm.value.rydwid
    leaderid.value = ruleForm.value.ryid ? ruleForm.value.ryid : null;
    chooseUserVisible.value = true;
  } else if (val == "02") {
    deptId.value = ruleForm.value.fqsgsid
    leaderid.value = ruleForm.value.ldid ? ruleForm.value.ldid : null;
    chooseUserVisible.value = true;
  }
}
//人员回显
const getSonValue = (value) => {
  if (zzlx.value == "01") {
    ruleForm.value.ryxm = value[0].userName;
    ruleForm.value.ryid = value[0].id;
    timelist.value[2].czrname = ruleForm.value.ryxm
  } else if (zzlx.value == "02") {
    ruleForm.value.ldxm = value[0].userName;
    ruleForm.value.ldid = value[0].id;
    timelist.value[1].czrname = ruleForm.value.ldxm
  }
};
// 关闭
const handleClose = () => {
  if (!props.isdisabled) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        ISbj.value = false
        ruleForm.value = {}
        ruleFormRef.value.resetFields()
        emits("changeAddVi", false);
      })
      .catch(() => {
        // catch error
      })
  } else {
    ISbj.value = false
    ruleForm.value = {}
    ruleFormRef.value.resetFields()
    emits("changeAddVi", false);
  }

};
// 保存
const handleSave = async (formEl, val) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      loading.value = true;
      ruleForm.value.zrslx = ruleForm.value.lxs
      ruleForm.value.xfzt = val
      ruleForm.value.files = ruleForm.value.files ? ruleForm.value.files.toString() : null
      if (props.title == "网签责任书新增") {
        postApi(ruleForm.value, "/mosty-jcgl/zrs/addZrs").then(() => {
          loading.value = false;
          ElMessage.success("新增成功");
          emits("changeAddVi", false);
          ISbj.value = false
          ruleForm.value = {}
          ruleFormRef.value.resetFields()
        }).catch(() => {
          loading.value = false;
        })
      } else {
        postApi(ruleForm.value, "/mosty-jcgl/zrs/editZrs").then(() => {
          loading.value = false;
          ElMessage.success("修改成功");
          emits("changeAddVi", false);
          ISbj.value = false
          ruleForm.value = {}
          ruleFormRef.value.resetFields()
        }).catch(() => {
          loading.value = false;
        })
      }
    } else {
      ElMessage.warning('请输入必填项！！！')
    }
  })
}
</script>
<style lang="scss" scoped>
// ::v-deep .edui-editor-iframeholder {
//   height: calc(100vh - 658px) !important;
// }
.dialog-box {
  z-index: 9999;
}

.bg_color {
  background: #fff !important;
}

.input_div {
  width: 646px;
  color: #131313;
  background-color: #d3dbdd;
  line-height: 1.5;
  font-size: 14px !important;
  border: 1px solid var(--el-color-primary);
  min-height: 115px;
  border-radius: 4px;
  padding: 5px 15px;

  div,
  span,
  font,
  p {
    font-size: 14px !important;
    line-height: 1.5 !important;
    text-indent: 0 !important;
  }
}

.top-btn {
  margin: 10px;
}

.btn-clas {
  padding: 10px 25px;
}

.config {
  height: 83vh;
  background-color: #fff;
  padding: 20px;
}

.box-big {
  width: 1439px;
  margin: 0 auto;
  display: flex;
  padding: 20px;
  height: 71vh;
}

.box-left {
  width: 66%;
  padding: 0 20px;
  border-right: 1px solid var(--el-color-primary);
  height: calc(100vh - 276px);
  overflow-y: auto;
}

.box_right {
  width: 35%;
  height: 65vh;
  overflow-y: auto;
  padding: 20px;
}

.top-word {
  display: flex;
  justify-content: space-between;
}

.word-box {
  width: 1021px;
  background-color: #f0f3f4;
}

::v-deep .el-radio.is-bordered.is-checked {
  background-color: var(--el-color-primary) !important;
  color: #fff !important;
}

::v-deep .el-radio__input.is-checked+.el-radio__label {
  color: #fff !important;
}

::v-deep .el-radio__input.is-checked .el-radio__inner {
  border-color: #fff !important;
}

.time-top {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.name-box {
  font-family: Microsoft YaHei, Microsoft YaHei;
  font-weight: bold;
  font-size: 14px;
  color: #191919;
}

.lable-time {
  display: inline-block;
  padding: 0px 10px;
  border-radius: 2px 2px 2px 2px;
  color: #fff;
  margin: 0px 10px;
}

.gren {
  background: #07877e;
}

.reds {
  background-color: #e91717;
}

.yess {
  background: #ebd0a1;
}

.time-ri {
  font-family: Microsoft YaHei, Microsoft YaHei;
  font-weight: 400;
  font-size: 14px;
  color: #191919;
}

.ldxm {
  font-weight: 400;
  font-size: 12px;
  margin: 10px;
}

::v-deep .el-card {
  background: #f0f3f4 !important;
  border-radius: 2px 2px 2px 2px !important;
}

::v-deep .edui-default .edui-editor-toolbarbox {
  position: none !important;
}
</style>
