<template>
  <div>
    <div class="dialog-h-content scroll-h">

      <el-form ref="ref_form"
               :inline="true"
               :model="formData"
               :rules="dataRule"
               class="div_form">

        <el-form-item label="政策级别"
                      label-width="150px"
                      prop="policyLevel">
          <el-select class="item_width_1"
                     v-model="formData.policyLevel"
                     placeholder="全部"
                     clearable>
            <el-option v-for="item in policyLevelArray"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>

        </el-form-item>

        <el-form-item label="政策日期"
                      label-width="150px"
                      prop="startDate">
          <el-date-picker v-model="formData.startDate"
                          class="item_width_2"
                          type="date"
                          value-format="yyyy-MM-dd"
                          value="yyyy-MM-dd"
                          placeholder="开始时间">
          </el-date-picker>
          <span class="data-tag">至</span>
          <el-date-picker v-model="formData.endDate"
                          class="item_width_2 data-tag"
                          type="date"
                          value-format="yyyy-MM-dd"
                          value="yyyy-MM-dd"
                          placeholder="结束时间">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="政策标题"
                      prop="title"
                      label-width="150px"
                      style="display: block">
          <el-input class="item_width_1"
                    placeholder="请输入政策标题"
                    v-model="formData.title">
          </el-input>
        </el-form-item>

        <el-form-item label="政策内容"
                      prop="content"
                      label-width="150px"
                      style="display: block">
          <el-input class="item_width_1"
                    type="textarea"
                    maxlength="1000"
                    show-word-limit
                    :rows="3"
                    placeholder="请输入政策内容"
                    v-model="formData.content"></el-input>
        </el-form-item>

        <div v-for="(item,index) in ruleList"
             :key="index">

          <el-form-item :label="'政策细则'+(index+1)"
                        prop="principalName"
                        label-width="150px"
                        style="display: block">
            <el-input class="item_width_short"
                      placeholder="请输入政策细则名称"
                      v-model="item.ruleName">
            </el-input>

            <el-button v-if="index!==0"
                       type="danger"
                       size="mini"
                       plain
                       style="margin-left:20px"
                       @click="delRule(index)">删除细则</el-button>
          </el-form-item>

          <el-form-item :label="'匹配规则'+(index+1)"
                        prop="principalName"
                        label-width="150px"
                        style="display: block">
            <rule :ref="'ref_rule'+index"></rule>
          </el-form-item>
          <div v-if="index===(ruleList.length-1)"
               class="btn-add-rule">
            <el-button type="primary"
                       size="mini"
                       plain
                       @click="addRule">增加细则</el-button>
          </div>
        </div>

        <el-form-item label="匹配资源类型"
                      prop="serviceScope"
                      label-width="150px"
                      style="display: block">
          <el-cascader class="item_width_1"
                       ref="myCascader"
                       v-model="demandIdArray"
                       :options="demandOptions"
                       :props="optionProps"
                       @change="handleCateSlect"></el-cascader>
        </el-form-item>

        <el-form-item class="block"
                      label="附件"
                      label-width="150px"
                      prop="attach">
          <el-upload class="upload-demo"
                     :action="uploadUlr"
                     accept=".doc,.pdf,.xls,.docx,.xlsx,.jpg,.png,.jpeg,.bmp,.mp4,.wma,.m4a,.mp3"
                     :on-success="handleFileSuccess"
                     :on-remove="handleFileRemove"
                     :limit="3"
                     :before-upload="beforeUpload"
                     :file-list="fileList">
            <el-button size="small"
                       :disabled="fileList.length===3"
                       type="primary">点击上传</el-button>
            <div slot="tip"
                 class="el-upload__tip">支持图片、word、pdf</div>
          </el-upload>
        </el-form-item>

      </el-form>

    </div>

    <div class="div_btn">
      <el-button size="small"
                 @click="handleCancle">取 消</el-button>
      <el-button size="small"
                 type="primary"
                 :disabled="btnDisable"
                 @click="handleComfirm">确 定</el-button>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { Loading } from 'element-ui' // 引入Loading服务
import { requestPost } from '@/js/dai/request'
import rule from './rule'



let loading // 加载动画
export default {
  data () {
    let endDisabledDate = (time) => {//这个关键属性我们一定要写在data的里面并且return的外面，这是动态改变区间的关键
      let nowData = Date.now()
      if (this.formData.serviceTimeStart) {
        let serviceTimeStart = new Date(this.formData.serviceTimeStart)
        return time.getTime() > nowData || time.getTime() < serviceTimeStart || time.getTime() === serviceTimeStart
      } else {
        return time.getTime() > nowData
      }

    }
    let startDisabledDate = (time) => {//这个关键属性我们一定要写在data的里面并且return的外面，这是动态改变区间的关键
      let nowData = Date.now()
      return time.getTime() > nowData
    }

    return {

      ruleList: [
        {
          ruleName: '',
          resiRuleList: [],
          houseRuleList: [],
          statRuleList: []
        }
      ],

      policyLevelArray: [],

      btnDisable: false,
      demandOptions: [],
      demandIdArray: [],

      optionProps: {
        multiple: true,
        // value: 'objectId',
        // label: 'objectName',
        // children: 'children',
        checkStrictly: true
      },

      formData: {
        policyLevel: '',//政府级别
        startDate: '',//起始时间yyyy-MM-dd	
        endDate: '',//截止时间yyyy-MM-dd	
        title: '',//
        content: '',//
        categoryList: [],
        attachmentList: [],
        ruleList: [],

      },

      endPickerOptions: {
        disabledDate: endDisabledDate
      },
      startPickerOptions: {
        disabledDate: startDisabledDate
      },

      fileList: [],
      uploadUlr: window.SITE_CONFIG['apiURL'] + '/oss/file/uploadvariedfile',

    }
  },

  watch: {
    "formData.serviceTimeEnd": function (val) {
      if (val && val != '') {
        let arrayTemp = val.split(' ')
        this.formData.serviceTimeEnd = arrayTemp[0] + ' 23:59:59'
      }

    },
  },
  components: { rule },
  async mounted () {
    this.startLoading()

    this.getDictOptions();
    await this.loadDemandoption()

    if (this.formType === 'add') {
      this.$refs.ref_form.resetFields();

    } else {
      this.loadFormInfo()

    }

    this.endLoading()

  },


  methods: {
    addRule () {
      let obj = {
        name: '',
        detail: []
      }

      this.ruleList.push(obj)
    },
    delRule (index) {
      this.ruleList.splice(index, 1);
    },

    async loadFormInfo () {
      const url = '/heart/policy/detail/' + this.policyId

      let params = {}

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {
        this.formData = data
      } else {
        this.$message.error(msg)
      }


    },

    async getDictOptions () {

      this.$http
        .post("/sys/dict/data/dictlist", {
          dictType: "policy_level",
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.policyLevelArray = res.data;
          }
        })
        .catch(() => {
          return this.$message.error("网络错误");
        });

    },


    // 获取服务范围树
    loadDemandoption () {
      const url = '/heart/icresidemanddict/demandoption'
      // const url = 'http://yapi.elinkservice.cn/mock/245/gov/org/isServiceProject/service/serviceScopeTree'
      let params = {}
      window.app.ajax.post(
        url,
        params,
        (data, rspMsg) => {

          this.demandOptions = this.getFlagData(
            this.getTreeData(data),
            "usableFlag"
          );
        },
        (rspMsg, data) => {
          this.$message.error(rspMsg)
        }
      )

    },


    handleCateSlect (val) {
      console.log("val", val);
      let arr = []
      val.forEach((item) => {
        let obj = {
          codePath: item.join(','),
          categoryCode: item[item.length - 1]
        }

        arr.push(obj)
      });

      console.log("arr", arr);
      this.formData.categoryList = arr

    },



    async handleComfirm () {


      this.handleAdd()

    },

    async handleAdd () {

      let ruleList = []
      let _this = this

      this.ruleList.forEach((oneRule, index) => {
        if (!oneRule.ruleName) {
          this.$message.error('政策细则不能为空')
          return false
        }
        let refObj = _this.$refs['ref_rule' + index][0]

        refObj.getRule()
        if (refObj.okflag) {
          oneRule.resiRuleList = refObj.resiRuleList
          oneRule.houseRuleList = refObj.houseRuleList
          oneRule.statRuleList = refObj.statRuleList

        } else {
          return false
        }
      });

      this.formData.ruleList = this.ruleList

      this.btnDisable = true
      setTimeout(() => {
        this.btnDisable = false
      }, 10000)
      this.$refs['ref_form'].validate((valid, messageObj) => {
        if (!valid) {
          app.util.validateRule(messageObj)
          this.btnDisable = false
        } else {
          this.addFuwu()

        }

      })

    },

    async addFuwu () {
      console.log(this.formData)



      const url = '/heart/policy/add'
      // const url = 'http://yapi.elinkservice.cn/mock/245/heart/icServiceProject/service/initiate'
      let params = {

        ...this.formData
      }

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {
        this.$message.success('新增成功')
        this.resetData()
        this.$emit('handleOk')
      } else {
        this.$message.error(msg)
      }
    },

    getTreeData (data) {
      if (!Array.isArray(data)) return [];
      let arr = data.map((item) => {
        let _item = {};
        if (item.children) {
          if (item.children.length === 0)
            _item = { ...item, children: undefined };
          else _item = { ...item, children: this.getTreeData(item.children) };
        } else {
          _item = { ...item };
        }
        return _item;
      });
      return arr;
    },
    getFlagData (data, flag) {
      if (!Array.isArray(data)) return [];
      let arr1 = data.filter((item) => item[flag]);
      let arr2 = arr1.map((item) => {
        if (item.children)
          return { ...item, children: this.getFlagData(item.children, flag) };
        else return item;
      });
      // console.log('arrr-oppp', arr2)
      return arr2;
    },

    beforeUpload (file) {
      const array = file.name.split('.')
      const extension = array[array.length - 1]

      const formatarray = ['jpg', 'png', 'jpeg', 'bmp', 'mp4', 'wma', 'm4a', 'mp3', 'doc', 'docx', 'xls', 'xlsx', 'pdf']

      if (formatarray.indexOf(extension) === -1) {
        this.$message.error('只支持图片、word、pdf')
        return false
      }

    },

    handleFileRemove (file) {

      if (file && file.status === "success") {
        this.fileList.splice(this.fileList.findIndex(item => item.uid === file.uid), 1)
      }
    },

    handleFileSuccess (res, file) {

      if (res.code === 0 && res.msg === 'success') {
        const array = file.name.split('.')
        const fileType = array[array.length - 1]

        const picArray = ['jpg', 'png', 'jpeg', 'bmp']
        const videoarray = ['mp4', 'wma', 'm4a']
        const docArray = ['doc', 'docx', 'xls', 'xlsx', 'pdf']
        const mp3Array = ['mp3']

        if (picArray.indexOf(fileType) > -1) {
          file.attachmentFormat = 'image'
        } else if (videoarray.indexOf(fileType) > -1) {
          file.attachmentFormat = 'video'
        } else if (docArray.indexOf(fileType) > -1) {
          file.attachmentFormat = 'doc'
        } else if (mp3Array.indexOf(fileType) > -1) {
          file.attachmentFormat = 'voice'
        }

        file.url = res.data.url
        file.type = fileType

        file.attachmentName = file.name
        file.attachmentType = file.type
        file.attachmentUrl = file.url

        this.fileList.push(file)
        console.log(this.fileList)
      } else this.$message.error(res.msg)
    },

    //下载
    handleFileDownload (file) {

      var a = document.createElement('a');
      var event = new MouseEvent('click');
      a.download = file.name;
      console.log(a)
      a.href = file.url;
      a.dispatchEvent(event);


    },
    handleCancle () {
      this.resetData()
      this.$emit('handleClose')

    },


    resetData () {
      this.ruleList = []
      this.formData = {
        policyLevel: '',//政府级别
        startDate: '',//起始时间yyyy-MM-dd	
        endDate: '',//截止时间yyyy-MM-dd	
        title: '',//
        content: '',//
        categoryList: [],
        attachmentList: [],
        ruleList: [],
      }
    },
    // 开启加载动画
    startLoading () {
      loading = Loading.service({
        lock: true, // 是否锁定
        text: '正在加载……', // 加载中需要显示的文字
        background: 'rgba(0,0,0,.7)' // 背景颜色
      })
    },
    // 结束加载动画
    endLoading () {
      // clearTimeout(timer);
      if (loading) {
        loading.close()
      }
    }
  },
  computed: {
    dataRule () {
      return {

        policyLevel: [
          { required: true, message: '政策级别不能为空', trigger: 'change' }
        ],
        startDate: [
          { required: true, message: '政策日期不能为空', trigger: 'change' }
        ],
        title: [
          { required: true, message: '政策标题不能为空', trigger: 'change' }
        ],


      }
    },


  },
  props: {

    policyId: {
      type: String,
      required: ''
    },

    formType: { //表单操作类型 add新增，edit编辑，detail详情,feedback反馈
      type: String,
      required: ''
    },

  }
}
</script>


<style lang="scss" scoped >
@import "@/assets/scss/modules/management/form-main.scss";

.btn-add-rule {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.item_width_short {
  width: 380px;
}
</style>
