<template>
  <div class="content-main announcementDetail">
    <el-tabs v-model="activeName" type="card">
      <el-tab-pane label="通知" name="first">
        <el-form
          :model="formData"
          ref="formData"
          label-width="210px"
          :rules="rules"
        >
          <el-row>
            <el-col :span="24">
              <el-form-item label="通知标题：" prop="title">
                <el-input
                  v-model="formData.title"
                  autocomplete="off"
                  :disabled="btnAction == '详情'"
                ></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="发布日期：" prop="fbrq">
                <el-date-picker
                  v-model="formData.fbrq"
                  style="width: 100%"
                  :disabled="btnAction == '详情'"
                  value-format="yyyy-MM-dd"
                  type="date"
                  placeholder="选择日期"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="发布人：" prop="fqr">
                <el-input
                  v-model="formData.fqr"
                  autocomplete="off"
                  :disabled="true"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="发布单位：" prop="fbdw">
                <el-input
                  v-model="formData.fbdw"
                  autocomplete="off"
                  :disabled="true"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24" class="tzdx">
              <el-form-item label="通知对象：">
                已选择{{ formData.jsdw.length }}个
                <span class="seeCLa" v-if="seeFlag" @click="seeFun(false)"
                  >查看全部</span
                >
                <span class="seeCLa" v-if="!seeFlag" @click="seeFun(true)"
                  >收起</span
                >
                <!-- <el-button type="primary"  @click="choose">选择</el-button> -->
                <!-- <el-radio
                  v-model="formData.fblx"
                  label="0"
                  @change="tzdxchange"
                  :disabled="btnAction == '详情'"
                  >全部</el-radio
                >
                <el-radio
                  v-model="formData.fblx"
                  label="1"
                  @change="tzdxchange"
                  :disabled="btnAction == '详情'"
                  >购销公司</el-radio
                >
                <el-radio
                  v-model="formData.fblx"
                  label="4"
                  @change="tzdxchange"
                  :disabled="btnAction == '详情'"
                  >区粮办</el-radio
                >
                <el-radio
                  v-model="formData.fblx"
                  label="2"
                  @change="tzdxchange"
                  :disabled="btnAction == '详情'"
                  >承储库</el-radio
                >

                <el-radio
                  v-model="formData.fblx"
                  label="3"
                  @change="tzdxchange"
                  :disabled="btnAction == '详情'"
                  >指定企业</el-radio
                > -->
              </el-form-item>
            </el-col>

            <el-col
              :span="24"
              v-if="
                (btnAction !== '详情' && formData.fblx !== '3') ||
                btnAction == '详情'
              "
            >
              <el-form-item
                prop="jsdw"
                :rules="[
                  {
                    required: true,
                    message: '请添加通知对象',
                    trigger: 'blur',
                  },
                ]"
              >
                <div
                  style="
                    border: 1px solid;
                    height: 25px;
                    padding: 15px;
                    overflow: hidden;
                    cursor: pointer;
                  "
                  id="tzdxDom"
                  @click="btnAction == '详情' ? choose1() : choose()"
                >
                  <span
                    v-if="formData.jsdw.length == 0"
                    style="
                      color: #666;
                      margin-top: -24px;
                      display: block;
                      margin-left: -10px;
                    "
                    >添加</span
                  >
                  <span
                    v-for="item in formData.jsdw"
                    style="
                      display: inline-block;
                      margin-right: 10px;
                      margin-bottom: 10px;
                    "
                  >
                    <el-tag>{{ item }}</el-tag>
                  </span>
                </div>
              </el-form-item>
            </el-col>
            <el-col v-else class="zdqyCl">
              <el-col :span="13">
                <el-form-item>
                  <el-cascader-panel
                    ref="cascaderAddr"
                    :options="kdOptions"
                    v-model="formData.jsdwbm"
                    @change="casChangeFn()"
                    :disabled="btnAction == '详情'"
                    :props="{
                      multiple: true,
                      emitPath: false,
                      checkStrictly: true,
                      value: 'orgCode',
                      label: 'orgName',
                      children: 'children',
                    }"
                  >
                  </el-cascader-panel>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item>
                  <div
                    style="
                      border: 1px solid;
                      height: 200px;
                      padding: 15px;
                      overflow-y: auto;
                    "
                  >
                    <span
                      v-for="item in formData.jsdw"
                      style="
                        display: inline-block;
                        margin-right: 10px;
                        margin-bottom: 10px;
                      "
                    >
                      <el-tag>{{ item }}</el-tag>
                    </span>
                  </div>
                </el-form-item>
              </el-col>
            </el-col>
            <el-col :span="24" class="upload-plan" style="margin-top: 20px">
              <el-form-item label="通知附件：">
                <el-upload
                  v-if="btnAction !== '详情'"
                  class="upload-demo"
                  ref="upload"
                  :action="uploadUrlBc"
                  :on-success="onSuccess1Bc"
                  :on-preview="handlePreviewBc"
                  :on-remove="handleRemoveBc"
                  :before-remove="beforeRemove1Bc"
                  :on-exceed="handleExceedBc"
                  :on-error="onError"
                  multiple
                  :file-list="fileList1Bc"
                  :auto-upload="true"
                >
                  <el-button size="small" type="primary" class="outButton"
                    >点击上传</el-button
                  >
                </el-upload>
                <el-row
                  v-for="(item, index) in fileList1Bc"
                  :key="index"
                  v-if="btnAction == '详情'"
                >
                  <span @click="viewFileFun(item.id)" style="cursor: pointer">{{
                    item.name
                  }}</span>
                </el-row>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="通知详情：" prop="fssj">
                <quill-editor
                  :disabled="btnAction == '详情'"
                  v-model="formData.nr"
                  ref="myQuillEditor"
                  id="myQuillEditor"
                  :options="quillOption"
                ></quill-editor>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row
            class="saveCancel"
            style="text-align: center; margin-top: 20px"
          >
            <el-col :span="24">
              <div class="grid-content bg-purple">
                <el-button
                  type="primary"
                  @click="saveBasic('formData')"
                  v-if="btnAction !== '详情'"
                >
                  <i class="iconfont iconbaocun"></i>
                  保存
                </el-button>
                <el-button
                  type="primary"
                  @click="saveBasic('formData', 'send')"
                  v-if="btnAction !== '详情'"
                >
                  <i class="iconfont icontijiao"></i>
                  发布
                </el-button>
                <el-button
                  type="primary"
                  class="iconfont iconfanhui"
                  @click="goBack"
                  >返回</el-button
                >
              </div>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="查看情况" name="second" v-if="btnAction == '详情'">
        <el-table
          tooltip-effect="dark"
          style="width: 100%"
          align="center"
          border
          stripe
          highlight-current-rowv-loading="tableLoading"
          :data="formData.childList"
        >
          <el-table-column label="序号" align="center" width="55">
            <template slot-scope="scope">
              <span>{{ scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            :show-overflow-tooltip="true"
            label="接收企业"
            prop="jsdw"
          ></el-table-column>
          <el-table-column
            align="center"
            :show-overflow-tooltip="true"
            label="是否接收"
            prop="isck"
          >
            <template slot-scope="scope">
              <span v-if="scope.row.isck == 0">{{ "否" }}</span>
              <span v-if="scope.row.isck == 1">{{ "是" }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            :show-overflow-tooltip="true"
            label="接收时间"
            prop="cksj"
          ></el-table-column>
          <el-table-column
            align="center"
            :show-overflow-tooltip="true"
            label="接收人"
            prop="ckr"
          ></el-table-column>
        </el-table>
        <el-row class="saveCancel" style="text-align: center">
          <el-col :span="24">
            <div class="grid-content bg-purple">
              <el-button
                type="primary"
                class="iconfont iconfanhui"
                @click="goBack"
                >返回</el-button
              >
            </div>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>

    <el-dialog title="通知对象" :visible.sync="dialogVisibleDx" width="70%">
      <tree-transfer
        ref="insideChooseProject"
        :datas="treeTransferData"
        :defaultProps="defaultProps"
        :checkedList="treeChecked"
      ></tree-transfer>

      <span slot="footer" style="text-align: center" class="dialog-footer">
        <el-button @click="dialogVisibleDx = false" size="small"
          >取 消</el-button
        >
        <el-button
          style="padding: 9px 15px !important"
          type="primary"
          @click="sureLb"
          size="small"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { quillEditor } from "vue-quill-editor";
import quillConfig from "@/utils/quill-config.js";
import treeTransfer from "./treeTransfer.vue";
import {
  getKdListTreeNew,
  getListData,
  detailInfo,
  saveData,
  updateData,
  deleteData,
  sendData,
  viewFile,
  viewFileData,
  viewAllFileData,
  listDevAndRef,
  listGroupOrg,
} from "@/api/publicfunction/announcement";
import { fileDownload, files, fileUpload } from "@/api/index";
export default {
  data() {
    return {
      seeFlag: true,
      // 穿梭框默认
      defaultProps: {
        id: "id",
        children: "children",
        label: "label",
        // pCode:"pid"
      },
      //穿梭框弹窗是否出现
      openDialog: false,
      // 穿梭框选中数据
      treeChecked: [],
      // 穿梭框数据
      treeTransferData: [
        {
          id: "1",
          label: "1",
          children: [
            {
              id: "1-1",
              label: "1-1",
              pid: "1",
            },
            {
              id: "1-2",
              label: "1-2",
              pid: "1",
            },
            {
              id: "1-3",
              label: "1-3",
              pid: "1",
            },
          ],
        },
        {
          id: "2",
          label: "2",
          children: [
            {
              id: "2-1",
              label: "2-1",
              pid: "2",
            },
            {
              id: "2-2",
              label: "2-2",
              pid: "2",
            },
            {
              id: "2-3",
              label: "2-3",
              pid: "2",
            },
          ],
        },
        {
          id: "3",
          label: "3",
          children: [
            {
              id: "3-1",
              label: "3-1",
              pid: "3",
            },
            {
              id: "3-2",
              label: "3-2",
              pid: "3",
            },
            {
              id: "3-3",
              label: "3-3",
              pid: "3",
            },
          ],
        },
      ],

      dialogVisibleDx: false,
      uploadUrlBc: `${fileUpload}`, //上传地址
      fileList1Bc: [],
      formData: {
        fbzt: "",
        jsdw: "",
        fbrq: "",
      },
      scspName: "",
      scfjName: "",
      dialogVisible: false,
      isImg: false,
      detailLoading: false,
      kdOptions: [],
      gxgsName: [],
      gxgsCode: [],
      cckName: [],
      cckCode: [],
      quillOption: quillConfig,
      activeName: "first",
      tableData: [],
      rules: {
        title: [{ required: true, message: "请输入通知标题", trigger: "blur" }],
        fbrq: [
          { required: true, message: "请选择发布时间", trigger: "change" },
        ],
        fblx: [
          { required: true, message: "请选择通知对象", trigger: "change" },
        ],
      },
      btnAction: "新增",
      qlbListName: [],
      qlbList: [],
      all: 0,
    };
  },
  components: {
    quillEditor,
    treeTransfer,
  },
  created() {
    this.getqlbList();
    getKdListTreeNew().then((res) => {
      res.data.forEach((item) => {
        if (item.children.length == 0) {
          item.children = null;
        } else {
          item.children.forEach((item1) => {
            if (item1.children.length == 0) {
              item1.children = null;
            } else {
              item1.children.forEach((item2) => {
                if (item2.children.length == 0) {
                  item2.children = null;
                }
              });
            }
          });
        }
      });
      this.kdOptions = res.data;
      this.gxgsName = [];
      this.gxgsCode = [];
      this.cckName = [];
      this.cckCode = [];
      this.kdOptions.forEach((item) => {
        if (item.orgType == "10190005") {
          this.gxgsName.push(item.orgName);
          this.gxgsCode.push(item.orgCode);
        } else if (item.orgType == "10190008") {
          this.cckName.push(item.orgName);
          this.cckCode.push(item.orgCode);
        }
        if (item.children) {
          item.children.forEach((item1) => {
            this.cckName.push(item1.orgName);
            this.cckCode.push(item1.orgCode);
          });
        }
      });
    });
    if (this.$route.query.action == "新增") {
      this.btnAction = "新增";
      this.dateFormat();
      this.formData.fqr = sessionStorage.getItem("userName");
      this.formData.fbdw = sessionStorage.getItem("orgName");
    } else if (this.$route.query.action == "修改") {
      this.btnAction = "修改";
      detailInfo(this.$route.query.id).then((res) => {
        this.formData = res;
        this.formData.jsdw = this.formData.jsdw.split(",");
        this.formData.jsdwbm = this.formData.jsdwbm.split(",");
        if (this.formData.fjid) {
          viewAllFileData(this.formData.fjid).then((res) => {
            this.fileList1Bc = res.data;
          });
        } else {
          this.fileList1Bc = [];
        }
      });
    } else if (this.$route.query.action == "详情") {
      this.btnAction = "详情";
      detailInfo(this.$route.query.id).then((res) => {
        this.formData = res;
        this.formData.jsdw = this.formData.jsdw.split(",");
        this.formData.jsdwbm = this.formData.jsdwbm.split(",");
        if (this.formData.fjid) {
          viewAllFileData(this.formData.fjid).then((res) => {
            this.fileList1Bc = res.data;
          });
        } else {
          this.fileList1Bc = [];
        }
      });
    }

    // this.getInitInfo();
  },
  methods: {
    seeFun(flag) {
      this.seeFlag = flag;
      let dom = document.getElementById("tzdxDom");
      if (flag) {
        dom.style.height = "25px";
      } else {
        dom.style.height = "auto";
      }
    },
    sureLb() {
      this.formData.jsdw = [];
      this.formData.jsdwbm = [];
      let arr = this.$refs["insideChooseProject"].getVal();
      arr.forEach((item) => {
        this.formData.jsdw.push(item.label);
        this.formData.jsdwbm.push(item.id);
      });
      console.log(this.formData);
      this.dialogVisibleDx = false;
    },
    // 触发穿梭框显示
    handleEditProject() {
      this.openDialog = true;
      if (this.$refs.insideChooseProject) {
        this.$refs.insideChooseProject.reset();
      }
      // 处理初始化选中的项目,若有初始选中数据则，在此添加初始选中的值
      this.treeChecked = [];
    },
    // 弹框确认获取已选中的树的list
    saveData() {
      console.log(this.$refs["insideChooseProject"].getVal());
    },
    choose1() {},
    choose() {
      // this.formData.jsdw = [];
      // this.formData.jsdwbm = [];
      this.treeTransferData = [];
      listGroupOrg().then((res) => {
        let data = res.data;
        this.all = 0;
        data.forEach((item, index) => {
          if (item.children.length > 0) {
            this.all += item.children.length;
            item.children.forEach((item1) => {
              item1.label = item1.orgName;
              item1.id = item1.orgCode;
            });
          } else {
            this.all += 1;
          }
          item.orgCode = item.orgCode == null ? index : item.orgCode;
          this.treeTransferData.push({
            id: item.orgCode,
            label: item.orgName,
            children: item.children,
          });
        });
      });
      this.dialogVisibleDx = true;
      // this.$refs["insideChooseProject"].getYx()
      this.$refs["insideChooseProject"].getLeft();
      this.$refs["insideChooseProject"].filterText1 = "";
      this.$refs["insideChooseProject"].filterText = "";
    },
    getqlbList() {
      listDevAndRef().then((res) => {
        res.data.map((item) => {
          this.qlbListName.push(item.orgName);
          this.qlbList.push(item.orgCode);
        });
      });
    },
    getInitInfo() {
      this.detailLoading = true;
      helpDetail(this.$route.query.wdId).then((res) => {
        this.formData = res;
        if (res.scfjid) {
          this.getFileFun(res.scfjid, "手册附件");
        }
        if (res.scspid) {
          this.getFileFun(res.scspid);
        }
        this.detailLoading = false;
      });
    },
    getFileFun(ids, mark) {
      getFileInfo(ids).then((res) => {
        if (res.infoCode == 200) {
          if (mark == "手册附件") {
            this.scfjName = res.data[0].name;
          } else {
            this.scspName = res.data[0].name;
            this.isImg = true; //默认的视频图片
          }
        } else {
          this.$message({
            message: res.msg,
            type: "error",
            duration: 2000,
          });
        }
      });
    },
    showVideo() {
      this.dialogVisible = true;
    },
    goBack() {
      this.$router.go(-1);
    },
    tzdxchange(val) {
      this.formData.jsdw = [];
      this.formData.jsdwbm = [];
      if (val == "0") {
        this.formData.jsdw = this.gxgsName.concat(this.cckName);
        this.formData.jsdwbm = this.gxgsCode.concat(this.cckCode);
      } else if (val == "1") {
        this.formData.jsdw = this.gxgsName;
        this.formData.jsdwbm = this.gxgsCode;
      } else if (val == "2") {
        this.formData.jsdw = this.cckName;
        this.formData.jsdwbm = this.cckCode;
      } else if (val == "3") {
      } else if (val == "4") {
        this.formData.jsdw = this.qlbListName;
        this.formData.jsdwbm = this.qlbList;
      }
      console.log(this.formData.jsdw, this.formData.jsdwbm, 99999);
    },
    casChangeFn() {
      console.log(this.formData.jsdwbm);
      this.formData.jsdw = [];
      let changeData = "";
      changeData = this.$refs["cascaderAddr"].getCheckedNodes();
      console.log(changeData);
      changeData.forEach((item) => {
        this.formData.jsdw.push(item.label);
      });
    },

    onSuccess1Bc(response, file, fileList) {
      console.log(file, fileList, "fileList");
      // if (response.infoCode === 200) {
      //   let arr = {
      //     id: response.data.id,
      //     name: response.data.name,
      //   };
      this.fileList1Bc = fileList;
      // }
    },
    handlePreviewBc(files) {
      window.location.href = `${file}/file/download?id=${
        files.response ? files.response.data.id : files.id
      }`;
      // window.location = `${files}/file/download?id=${this.formInline.bcfj}`;
    },
    handleRemoveBc(file, fileList) {
      this.fileList1Bc = fileList;
    },
    beforeRemove1Bc(file, fileList) {
      // if (this.showLock) {
      //   return false;
      // } else {
      return this.$confirm(`确定移除 ${file.name}？`);
      // }
    },
    handleExceedBc(files, fileList) {
      // this.$message.warning(
      //   `当前限制选择1个文件，本次已经选择了 ${files.length} 个文件`
      // );
    },
    onError(err, file, fileList) {
      this.$message({
        message: "上传失败",
        type: "error",
        duration: 2000,
      });
    },
    viewFileFun(fileId) {
      window.location = `${files}/file/download?id=${fileId}`;
    },
    saveBasic(formName, action) {
      if (this.fileList1Bc.length > 0) {
        this.formData.fjid = "";
        let arr = [];
        this.fileList1Bc.forEach((item) => {
          arr.push(item.id ? item.id : item.response.data.id);
        });
        console.log(this.fileList1Bc, "this.fileList1Bc");
        this.formData.fjid = arr.join(",");
        console.log(this.formData.fjid, "this.formData.fjid");
      } else {
        this.formData.fjid = "";
      }
      this.$refs[formName].validate((valid) => {
        if (this.btnAction == "新增") {
          if (valid) {
            if (action) {
              let params = JSON.parse(JSON.stringify(this.formData));

              params.jsdw = params.jsdw.join(",");
              params.jsdwbm = params.jsdwbm.join(",");
              params.fbzt = "1";
              saveData(params)
                .then((response) => {
                  if (response.code == 200) {
                    this.$router.push({
                      path: "announcement",
                    });
                    this.$message({
                      showClose: true,
                      message: "提交成功！",
                      type: "success",
                    });
                  }
                })
                .catch((e) => {});
            } else {
              let params = JSON.parse(JSON.stringify(this.formData));
              params.jsdw = params.jsdw.join(",");
              params.jsdwbm = params.jsdwbm.join(",");
              params.fbzt = "0";
              saveData(params)
                .then((response) => {
                  if (response.code == 200) {
                    this.$router.push({
                      path: "announcement",
                    });
                    this.$message({
                      showClose: true,
                      message: "保存成功！",
                      type: "success",
                    });
                  }
                })
                .catch((e) => {});
            }
          } else {
            return false;
          }
        } else if (this.btnAction == "修改") {
          if (valid) {
            if (action) {
              let params = JSON.parse(JSON.stringify(this.formData));

              params.jsdw = params.jsdw.join(",");
              params.jsdwbm = params.jsdwbm.join(",");
              params.fbzt = "1";
              updateData(params)
                .then((response) => {
                  if (response.code == 200) {
                    this.$router.push({
                      path: "announcement",
                    });
                    this.$message({
                      showClose: true,
                      message: "提交成功！",
                      type: "success",
                    });
                  }
                })
                .catch((e) => {});
            } else {
              let params = JSON.parse(JSON.stringify(this.formData));

              params.jsdw = params.jsdw.join(",");
              params.jsdwbm = params.jsdwbm.join(",");
              params.fbzt = "0";
              updateData(params)
                .then((response) => {
                  if (response.code == 200) {
                    this.$router.push({
                      path: "announcement",
                    });
                    this.$message({
                      showClose: true,
                      message: "保存成功！",
                      type: "success",
                    });
                  }
                })
                .catch((e) => {});
            }
          } else {
            return false;
          }
        }
      });
    },
    dateFormat() {
      let date = new Date();
      let year = date.getFullYear();
      /* 在日期格式中，月份是从0开始的，因此要加0
       * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
       * */
      let month =
        date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1;
      let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      let hours =
        date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
      let minutes =
        date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
      let seconds =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      // 拼接
      // return (year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds)
      this.formData.fbrq = year + "-" + month + "-" + day;
    },
  },
};
</script>
<style lang="scss" scoped>
.seeCLa {
  color: #409eff;
  cursor: pointer;
}
.el-form-item {
  margin-bottom: 0px;
  .el-form-item__label {
    line-height: 30px;
    color: #333 !important;
  }
  .el-form-item__content {
    line-height: 30px;
  }
}
.announcementDetail /deep/.ql-editor {
  min-height: 220px;
}
.ql-toolbar.ql-snow {
  // display: none;
}
.ql-toolbar.ql-snow + .ql-container.ql-snow {
  border-top: 1px solid #ccc !important;
}
.zdqyCl /deep/.el-cascader-menu__wrap {
  height: 222px !important;
}
.zdqyCl /deep/.el-cascader-menu__list {
  padding: 0px 0 18px 0 !important;
}
.tzdx /deep/ .el-form-item__error {
  color: #f56c6c;
  font-size: 12px;
  line-height: 1;
  padding-top: 4px;
  position: absolute;
  top: 10px;
  left: 80px;
}
</style>
<style>
.upload-plan {
  position: relative;
}
.upload-plan .el-upload-list {
  width: 75%;
}
.upload-plan .view-btn {
  position: absolute;
  right: 0;
  top: 40px;
}
</style>