<template>
  <div class="container add-research">
    <el-card>
      <el-form :model="ruleForm" :rules="rules" ref="ruleFormList" label-width="100px" class="demo-ruleForm">
        <el-form-item label="所属行业：" prop="industry">
          <el-select placeholder="请选择行业" style="width: 396px" clearable v-model="ruleForm.industry" @change="changeHandel">
            <el-option v-for="item in chartPermissionList" :label="item.PermissionName" :key="item.PermissionName" :value="item.PermissionName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="调研主题：" prop="theme">
          <el-input style="width: 396px" v-model="ruleForm.theme" placeholder="请输入调研主题"></el-input>
        </el-form-item>
        <el-form-item label="预期时间：" prop="date">
          <el-input v-model="ruleForm.date" style="width: 396px" placeholder="请输入预期活动时间"></el-input>
        </el-form-item>
        <el-form-item label="调研形式：" prop="modality">
          <el-radio-group v-model="ruleForm.modality">
            <el-radio v-for="item in modalityRadio" :key="item.id" :label="item.id">{{ item.name }}</el-radio>
          </el-radio-group>
          <el-input v-model="ruleForm.city" v-if="ruleForm.modality == 2" style="width: 248px; margin-left: 10px" placeholder="请输入调研城市,多个城市以','隔开"></el-input>
        </el-form-item>
        <el-form-item label="主题标签：">
          <div style="display: flex; align-items: center; flex-wrap: wrap">
            <el-form-item prop="property">
              <el-cascader
                key="multipleTrue"
                style="margin: 0 15px 10px 0"
                v-model="ruleForm.property"
                :disabled="selectDisabled"
                @change="propertyChange"
                placeholder="请选择产业名称"
                :show-all-levels="false"
                :options="industryArr"
                :props="{ ...defaultProps, multiple: true }"
                filterable
              >
              </el-cascader>
            </el-form-item>
            <el-form-item>
              <el-select style="margin: 0 15px 10px 0" v-model="ruleForm.mark" :disabled="selectDisabled" @focus="markSelectFocus" multiple placeholder="请选择关联标的">
                <el-option v-for="item in markOptions" :key="item.IndustrialSubjectId" :value="item.IndustrialSubjectId" :label="item.SubjectName"> </el-option>
              </el-select>
            </el-form-item>
            <div v-for="(item, index) in addSubjectData" :key="index" style="display: inline-block">
              <el-input style="width: 220px; margin: 0 5px 10px 0" v-model="item.subjectVal" placeholder="请输入标的名称" type="text"> </el-input>
              <img @click="deleteSubject(item, index)" style="width: 18px; margin-right: 20px; vertical-align: middle" src="~@/assets/img/icons/delete-Item.png" />
            </div>
            <el-tooltip class="item" effect="dark" content="添加标的" placement="top-start">
              <img @click="addLabelClick" class="editsty" src="~@/assets/img/set_m/add_ico.png" style="margin: 0 10px 10px" />
            </el-tooltip>
          </div>
          <div style="display: flex; align-items: center; margin-top: 10px">
            <el-checkbox v-model="ruleForm.isMark">小程序内显示标的名称</el-checkbox>
            <el-checkbox style="margin-left: 10px" v-model="radioTemporary">临时标签</el-checkbox>
            <el-input style="width: 300px; margin: 0 10px" v-model="valTemporary" @focus="radioTemporary = true" placeholder="请输入标签名称" type="text"></el-input>
            <div class="editsty" @click="dialogVisibleSubject = true">查询标的</div>
          </div>
        </el-form-item>
        <el-form-item label="活动可见：" prop="checkedCities">
          <div style="display: flex">
            <span style="width: 70px" class="text-right"> 套餐类型： </span>
            <el-checkbox :indeterminate="isIndeterminate" v-model="ruleForm.checkAll" @change="handleCheckAllChange" :disabled="checkAllIs" style="margin-right: 30px">全选</el-checkbox>
            <el-checkbox-group v-model="ruleForm.checkedCities" @change="handleCheckedCitiesChange">
              <el-checkbox v-for="item in cities" :label="item.CustomerTypeId" :key="item.CustomerTypeId">
                {{ item.CustomerName }}
                <el-tooltip :content="item.ExplainSpecial" placement="top-start" v-if="item.ExplainSpecial">
                  <i class="el-icon-info" />
                </el-tooltip>
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </el-form-item>
        <el-form-item label="行程安排：" prop="Poster">
          <el-upload
            :action="baseApi + '/resource/image/upload'"
            list-type="picture-card"
            :class="{ disabled: uploadDisabled }"
            :on-preview="handlePictureCardPreview"
            :on-success="handleUploadPosterSuccess"
            :on-remove="handlePosterRemove"
            :file-list="ruleForm.Poster"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog customClass="custom-addPoster" :visible.sync="dialogVisible" :modal-append-to-body="false">
            <div class="addPoster-img">
              <img width="100%" :src="dialogImageUrl" />
            </div>
          </el-dialog>
        </el-form-item>
        <div style="text-align: center; margin-top: 30px">
          <el-button type="primary" @click="submitForm('保存')">保存</el-button>
          <el-button type="primary" v-if="publishStatus" @click="submitForm('发布')">发布</el-button>
          <el-button @click="cancelBtn">取消</el-button>
        </div>
      </el-form>
    </el-card>
    <el-dialog width="500px" v-dialogDrag :close-on-click-modal="false" :modal-append-to-body="false" center title="查询标的" :visible.sync="dialogVisibleSubject" :before-close="handleCloseSubject">
      <div>
        <el-select style="width: 100%" v-model="addSubjectName" remote :remote-method="remoteMethod" clearable filterable @change="searchInfo" placeholder="请输入标的名称">
          <el-option v-for="item in addSubjectOptions" :key="item.IndustrialSubjectId" :label="item.SubjectName" :value="item.SubjectName"> </el-option>
        </el-select>
      </div>
      <p class="subject-text" v-if="isShowSubject">暂无数据</p>
      <template v-else>
        <p class="subject-text" v-for="(item, index) in nameSubjectOptions" :key="index">{{ item.Name }} : {{ item.value }}</p>
      </template>
      <p style="padding-bottom: 50px"></p>
    </el-dialog>
  </div>
</template>

<script>
import { raiInterface, raiSpecial } from "@/api/api.js";
import CryptoJS from "@/api/crypto.js";
export default {
  name: "",
  components: {},
  props: {},
  data() {
    return {
      baseApi: process.env.API_ROOT,
      ruleForm: {
        theme: "", //主题
        industry: "", //行业
        date: "", //时间
        property: [], //产业
        mark: [], //标的
        checkAll: true, ////套餐类型
        checkedCities: [], //套餐类型
        Poster: [],
        modality: "", //调研形式
        city: "", //城市
        isMark: false, //小程序内显示标的名称
      },
      rules: {
        industry: [{ required: true, message: "请选择行业", trigger: "change" }],
        theme: [{ required: true, message: "请输入调研主题", trigger: "blur" }],
        date: [{ required: true, message: "请输入预期活动时间", trigger: "blur" }],
        checkedCities: [{ required: true, message: "请选择套餐类型", trigger: "change" }],
        property: [{ required: true, message: "请选择产业名称", trigger: "change" }],
        modality: [{ required: true, message: "请选择调研形式", trigger: "change" }],
        Poster: [{ required: true, message: "请上传行程", trigger: "change" }],
      },
      dialogImageUrl: "",
      dialogVisible: false,
      chartPermissionList: [],
      defaultProps: {
        label: "PermissionName",
        children: "List",
        value: "ChartPermissionId",
      },
      markOptions: [],
      industryArr: [],
      radioTemporary: false, //临时标签
      valTemporary: "", //标签名称
      cities: [],
      isIndeterminate: false,
      dialogVisibleSubject: false,
      addSubjectName: "",
      addSubjectOptions: "",
      nameSubjectOptions: [],
      isShowSubject: false,
      ListSubject: [],
      checkedCitiesTwo: "",
      modalityRadio: [
        { name: "线上", id: 1 },
        { name: "线下", id: 2 },
      ],
      publishStatus: true,
      addSubjectData: [],
    };
  },
  computed: {
    uploadDisabled: function () {
      return this.ruleForm.Poster.length > 0;
    },
  },
  watch: {
    radioTemporary() {
      if (this.radioTemporary) {
        this.selectDisabled = true;
      } else {
        this.valTemporary = "";
        this.selectDisabled = false;
      }
    },
    "ruleForm.modality": {
      handler(newval) {
        if (newval == 1) {
          this.ruleForm.city = "";
        }
      },
      deep: true,
    },
  },
  created() {},
  mounted() {
    this.customerTypelist();
    this.chartPermission();
    this.getIndustry();
    if (this.$route.query.id) {
      this.themeDetails(this.$route.query.id);
    }
    if (this.$route.query.isShow == 1) {
      this.publishStatus = false;
    }
  },
  methods: {
    //获取行业
    chartPermission() {
      raiInterface.getActivitySpecial().then((res) => {
        if (res.Ret === 200) {
          this.chartPermissionList = res.Data.List;
        }
      });
    },
    /* 获取全部的行业 */
    getIndustry() {
      raiInterface.getListIndustrial().then((res) => {
        if (res.Ret === 200) {
          this.industryArr = res.Data.List || [];
        }
      });
    },
    //点击添加标的的下拉选择框
    markSelectFocus() {
      if (!this.ruleForm.property.length) {
        this.$message.error("请先选择产业");
      } else {
        let arr = [];
        arr = this.ruleForm.property.map((item) => {
          return item[1];
        });
        raiInterface
          .getindustrialSubjectlistIds({
            IndustrialManagementIdStr: arr.join(","),
          })
          .then((res) => {
            if (res.Ret === 200) {
              this.markOptions = res.Data.List || [];
            }
          });
      }
    },
    //获取多选的客户列表
    customerTypelist() {
      raiInterface.customerTypelist({ IsZxdy: true }).then((res) => {
        if (res.Ret === 200) {
          this.ruleForm.checkedCities = res.Data.List && res.Data.List.map((item) => item.CustomerTypeId);
          this.cities = res.Data.List;
        }
      });
    },
    // 上传成功回调
    handleUploadPosterSuccess(response, file, fileList) {
      let upload_list = [];
      fileList.forEach((item) => {
        let obj = {
          ...item,
          response: process.env.NODE_ENV === "production" ? JSON.parse(CryptoJS.Des3Decrypt(item.response)) : item.response,
        };
        upload_list.push(obj);
      });
      console.log(upload_list);
      this.ruleForm.Poster = upload_list.map((item) => {
        return { name: item.response.Data.ResourceName, ...item };
      });
    },
    // 删除上传的
    handlePosterRemove(file, fileList) {
      this.ruleForm.Poster = fileList;
    },
    //预览查看
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //全选框
    handleCheckAllChange(val) {
      if (val) {
        let newCodeList = this.cities.map((item) => item.CustomerTypeId);
        this.ruleForm.checkedCities = newCodeList;
      } else {
        this.ruleForm.checkedCities = [];
      }
      this.checkedCitiesTwo = this.ruleForm.checkedCities.join(",");
      this.isIndeterminate = false;
    },
    //全选框
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.ruleForm.checkAll = checkedCount === this.cities.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
    },
    //弹框的删除标的
    async remoteMethod(query) {
      if (query !== "") {
        const res = await raiInterface.industrialSubjectSearch({
          KeyWord: query,
        });
        if (res.Ret === 200) {
          this.addSubjectOptions = res.Data.List || [];
        }
      }
    },
    //弹框的表的 change 事件
    async searchInfo(val) {
      if (val !== "") {
        const res = await raiInterface.industrialSubjectSearchInfo({
          KeyWord: val,
        });
        if (res.Ret === 200) {
          this.isShowSubject = res.Data.List ? false : true;
          let arrList = [];
          arrList = res.Data.List
            ? res.Data.List.map((item) => {
                let arr = [];
                item.List.forEach((key) => {
                  arr.push(key.Name);
                });
                return {
                  ...item,
                  value: arr.join(","),
                };
              })
            : [];
          this.nameSubjectOptions = arrList;
        }
      } else {
        this.nameSubjectOptions = [];
      }
    },
    //获取调研主题详情
    async themeDetails(id) {
      const res = await raiSpecial.specialDetail({ ActivityId: id });
      if (res.Ret === 200) {
        let { Data } = res;
        let checkedCount = Data.CustomerTypeIds ? res.Data.CustomerTypeIds.split(",").length : "";
        let checkAll = checkedCount === this.cities.length;
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
        this.ruleForm = {
          theme: Data.ResearchTheme, //主题
          industry: Data.ChartPermissionName, //行业
          date: Data.ActivityTimeText, //时间
          property: Data.ListIndustrial ? Data.ListIndustrial.map((item) => [item.ChartPermissionId, item.IndustrialManagementId]) : [], //产业
          mark: Data.ListSubject ? Data.ListSubject.map((item) => item.IndustrialSubjectId) : [], //标的
          checkAll, ////套餐类型
          checkedCities: Data.CustomerTypeIds.split(",").map((item) => Number(item)), //套餐类型
          Poster: [{ name: "xxx.jpeg", url: Data.TripImgLink }],
          modality: Data.SpecialType,
          city: Data.City,
          isMark: Data.IsShowSubjectName == 1 ? true : false,
        };
        this.valTemporary = Data.TemporaryLabel;
        this.radioTemporary = this.valTemporary ? true : false;
        Data.TemporarySubject &&
          Data.TemporarySubject.split(",").forEach((item) => {
            this.addSubjectData.push({ subjectVal: item });
          });
        if (this.ruleForm.mark.length) {
          this.markSelectFocus();
        }
      }
    },
    handleCloseSubject() {
      this.nameSubjectOptions = [];
      this.addSubjectName = "";
      this.addSubjectOptions = [];
      this.dialogVisibleSubject = false;
    },
    //保持或者发布
    submitForm: _.debounce(function (type) {
      if (this.selectDisabled) {
        if (!this.valTemporary) return this.$message.error("请输入临时标签");
        let validateFieldList = [];
        this.$refs.ruleFormList.validateField(["industry", "theme", "date", "checkedCities", "Poster", "modality"], (valid) => {
          validateFieldList.push(valid);
        });
        if (this.ruleForm.modality == 2 && !this.ruleForm.city) {
          return this.$message.error("请输入调研城市");
        }
        let isPost = validateFieldList.every((item) => item === "");
        if (isPost) {
          this.postPublish(type);
        }
      } else {
        this.$refs.ruleFormList.validate((valid) => {
          if (valid) {
            if (this.ruleForm.modality == 2 && !this.ruleForm.city) {
              return this.$message.error("请输入调研城市");
            }
            this.postPublish(type);
          } else {
            return false;
          }
        });
      }
    }, 500),
    async postPublish(type) {
      let arr = this.ruleForm.property.map((item) => {
        return item[1];
      });
      let PosterList = this.ruleForm.Poster.map((item) => {
        if (item.response) {
          return item.response.Data.ResourceUrl;
        } else {
          return item.url;
        }
      });
      let subjectData = [];
      this.addSubjectData.forEach((item) => subjectData.push(item.subjectVal));
      const res = await raiSpecial.specialPreserveAndPublish({
        ActivityId: Number(this.$route.query.id) || 0,
        ActivityTimeText: this.ruleForm.date,
        CustomerTypeIds: this.ruleForm.checkedCities.join(","),
        TemporaryLabel: this.valTemporary,
        TripImgLink: PosterList.join(","),
        IndustrialSubjectIdS: this.ruleForm.mark.join(","),
        IndustrialManagementIdS: arr.join(","),
        DoType: type == "发布" ? 1 : 0,
        PermissionName: this.ruleForm.industry,
        ResearchTheme: this.ruleForm.theme,
        SpecialType: this.ruleForm.modality,
        City: this.ruleForm.city,
        IsShowSubjectName: this.ruleForm.isMark ? 1 : 0,
        TemporarySubject: subjectData.join(","),
      });
      if (res.Ret === 200) {
        this.$message.success(type + "成功");
        this.$router.back();
      }
    },
    //点击取消的事件
    cancelBtn() {
      this.$router.back();
    },
    //点击添加标的
    addLabelClick() {
      this.addSubjectData.push({ subjectVal: "" });
    },
    //删除新增的主题标签
    deleteSubject(index, item) {
      this.addSubjectData.splice(index, 1);
    },
  },
};
</script>
<style lang="scss">
.el-form-item__label:before {
  display: none;
}
.el-upload {
  width: 100px;
  height: 100px;
  line-height: 100px;
}
.disabled .el-upload--picture-card {
  display: none;
}
.custom-addPoster {
  background-color: rgba(0, 0, 0, 0) !important;
  box-shadow: none !important;
  width: 70%;
  .el-dialog__header {
    display: none;
  }
  .el-dialog__body {
    padding: 0 !important;
  }
}
</style>
<style scoped lang="scss">
.add-research {
  .subject-text {
    padding-top: 20px;
  }
  .addPoster-img {
    width: 100%;
    height: 75vh;
    img {
      height: 100%;
    }
  }
}
</style>
