<template>
  <ele-modal
    :title="dialogTitle"
    :visible.sync="addMatterDialog"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    width="80%"
  >
    <el-form
      :model="formData"
      v-loading="dialogLoading"
      ref="contentConfigForm"
      label-width="100px"
      :show-message="false"
      :rules="contentConfigFormRules"
    >
      <el-row>
		<el-col :span="7">
		  <el-form-item label="规则编码" prop="name">
		    <el-input
		      v-model="formData.code"
		      size="small"
		      :disabled="true"
		    ></el-input>
		  </el-form-item>
		</el-col>
        <el-col :span="6">
          <el-form-item label="规则名称" prop="name">
            <el-input
              v-model="formData.name"
              placeholder="请输入"
              size="small"
              :disabled="isBindPlan"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="规则类型" prop="ruleType">
			  <DictSelection dictName="规则类型" clearable v-model="formData.ruleType">
			  </DictSelection>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="状态" prop="status" label-width="70px">
            <el-switch
              v-model="formData.status"
              active-text="生效"
              inactive-text="失效"
              :active-value="1"
              :inactive-value="0"
            >
            </el-switch>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="周期" prop="cycleValue">
            <rule-cycle
              ref="cycleMultipleRef"
              :formData="formData"
              :pageType="pageType"
              :isBindPlan="isBindPlan"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-table
        ref="multipleTable"
        v-if="formData.ruleType !== 4"
        :data="formData.ruleItems"
        tooltip-effect="dark"
        style="width: 95%; margin: auto"
        border
        :header-cell-style="{ background: '#F0F3F3' }"
      >
        <el-table-column type="index" width="100" align="center">
          <template slot="header">
            <el-button type="text" @click="addItem" icon="el-icon-plus" :disabled="isBindPlan"
              >新增</el-button
            >
          </template>
        </el-table-column>
        <el-table-column prop="name" label="事项">
          <template slot-scope="scope">
            <el-form-item
              :prop="'ruleItems.' + scope.$index + '.name'"
              label-width="0"
              :rules="contentConfigFormRules.name"
            >
              <span v-if="scope.row.readonly">{{ scope.row.name }}</span>
              <el-input
                v-if="!scope.row.readonly"
                size="small"
                placeholder="请输入"
                v-model="scope.row.name"
                :disabled="isBindPlan"
              ></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="内容">
          <template slot-scope="scope">
            <el-form-item
              :prop="'ruleItems.' + scope.$index + '.content'"
              label-width="0"
              :rules="contentConfigFormRules.content"
            >
              <span v-if="scope.row.readonly">{{ scope.row.content }}</span>
              <el-input
                v-if="!scope.row.readonly"
                size="small"
                placeholder="请输入"
                v-model="scope.row.content"
                :disabled="isBindPlan"
              ></el-input>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column prop="norm" label="标准">
          <template slot-scope="scope">
            <el-form-item
              :prop="'ruleItems.' + scope.$index + '.norm'"
              label-width="0"
              :rules="contentConfigFormRules.norm"
            >
              <span v-if="scope.row.readonly">{{ scope.row.norm }}</span>
              <el-input
                v-if="!scope.row.readonly"
                size="small"
                placeholder="请输入"
                v-model="scope.row.norm"
                :disabled="isBindPlan"
              ></el-input>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column width="200" label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="delItem(scope.$index)" size="small" :disabled="isBindPlan"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-form>
	 <template v-slot:footer>
	   <el-button @click="handleClose">取消</el-button>
	   <el-button type="primary" @click="dataKeep">
	     保存
	   </el-button>
	 </template>
  </ele-modal>
</template>
<script>
import RuleCycle from './rule-cycle'
import { deepClone } from '@/utils/index'
import { saveOrUpdate , getCode , getDetail  } from '@/api/ruleManagement/matter'

export default {
  components: {  RuleCycle },
  props: {
    pageType: {
      type: String,
      default: ''
    },
    infoData: {
      type: Object,
      default: () => {
        return {}
      }
    },
    dialogTitle: {
      type: String,
      default: '新建规则'
    },
    dialogLoading: {
      type: Boolean,
      default: () => {
        return false
      }
    }
  },
  data () {
		// 默认表单数据
		const defaultForm = {
		  code:'',
		  name: '',
		  ruleType: '1',
		  status: 1,
		  cycleValue: undefined,
		  cycleType: 1,
		  contentImage: {},
		  ruleCycleList: [], // 规则周期日期值
		  ruleItems: [
		    {
		      name: '', // 巡点检事项
		      content: '', // 巡点检内容
		      norm: '', // 巡点检标准
		    }
		  ]
		};
    return {
      addMatterDialog: false,
      cycleValue: '',
      uploadList: [],
      formData: {},
      contentConfigFormRules: {
        name: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
        ruleType: [
          { required: true, message: '请选择规则类型', trigger: 'change' }
        ],
        cycleValue: [
          { required: true, message: '请输入巡点检周期', trigger: 'blur' }
        ],
        // contentImage: [
        //   { required: false, message: '请上传图片', trigger: 'blur' }
        // ],
        status: [{ required: true }],
        name: [
          { required: true, message: '请输入巡点检事项', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入巡点检内容', trigger: 'blur' }
        ],
        norm: [{ required: true, message: '请输入巡点检标准', trigger: 'blur' }]
      },
      isBindPlan:false
    }
  },
	watch: {

	},
  methods: {
		openDialog(row,type){
			this.addMatterDialog = true
			if(type !='add'){
				this.getRuleInfo(row.id,type)
			}else{
				this.formData = {...this.defaultForm}
				this.$set(this.formData,'status',1)
				this.$set(this.formData,'ruleType','1')
				this.$refs.contentConfigForm && this.$refs.contentConfigForm.resetFields()
			}
			if(type!='edit'){
				this.getOrderCode()
			}
		},

	async getRuleInfo(id,type){
		const data = await getDetail(id)
		this.formData = data
		this.formData.ruleType = JSON.stringify(this.formData.ruleType)
		if(type=='clone'){
			delete this.formData.id
		}
	},

	async getOrderCode () {
	  const data = await getCode('rule_code');
	  this.$set(this.formData, 'code', data);
	},

    handleClose () {
      this.addMatterDialog = false
      this.$emit('handleClose')
    },
    addItem () {
      if (this.formData.ruleItems) {
        this.formData.ruleItems.push({
          name: '', // 巡点检事项
          content: '', // 巡点检内容
          norm: '', // 巡点检标准
          readonly: false
        })
      } else {
        let arr = [
          {
            name: '', // 巡点检事项
            content: '', // 巡点检内容
            norm: '', // 巡点检标准
          }
        ]
        this.$set(this.formData,'ruleItems',arr)
        // this.formData.ruleItems =
      }
    },
    saveItem (index, row) {
      this.$nextTick(() => {
        let flag = false
        let name = row.name
        let content = row.content
        let norm = row.norm
        flag = name && content && norm
        this.$refs.contentConfigForm.validate(valid => {
          if (valid || flag) {
            this.$set(this.formData.ruleItems[index], 'readonly', true)
          }
        })
      })
    },
    upload (data) {
      if (data && data[0]?.accessUrl) {
        this.formData.contentImage = data
      } else {
        this.formData.contentImage = {}
      }
      this.$nextTick(() => {
        this.$refs.contentConfigForm.validateField('contentImage')
      })
      console.log(this.formData.contentImage)
    },
    editItem (index) {
      this.$nextTick(() => {
        this.$set(this.formData.ruleItems[index], 'readonly', false)
      })
    },
    delItem (index) {
      this.formData.ruleItems.splice(index, 1)
    },

    // 保存
    dataKeep () {
      let form = deepClone(this.formData)
      form.cycle = this.$refs.cycleMultipleRef.ruleCycleList
      switch(form.cycleType){
          case 1:
              if(form.cycle[0].minute===''){
                 this.$message.warning('周期信息需补充完整！')
                 return;
              }
              break;
          case 2:
              if(form.cycle[0].hour===''||form.cycle[0].minute===''){
                 this.$message.warning('周期信息需补充完整！')
                 return;
              }
              break;
          case 4:
              if(form.cycle[0].day===''||form.cycle[0].hour===''||form.cycle[0].minute===''){
                 this.$message.warning('周期信息需补充完整！')
                 return;
              }
              break;
          case 5:
              if(form.cycle[0].month===''||form.cycle[0].day===''||form.cycle[0].hour===''||form.cycle[0].minute===''){
                 this.$message.warning('周期信息需补充完整！')
                 return;
              }
              break;
          case 11:
               let flg = false
              form.cycle.map((item,index)=>{
                  if(item.hour===''||item.minute===''){
                     flg = true
                  }
              })
              if(flg){
                this.$message.warning('周期信息需补充完整！')
                return;
              }
              break;
          case 13:
               let flag = false
              form.cycle.map((item,index)=>{
                  if(item.day===''||item.hour===''){
                     flag = true
                  }
              })
              if(flag){
                this.$message.warning('周期信息需补充完整！')
                return;
              }
              break;
          case 14:
               let fla = false
              form.cycle.map((item,index)=>{
                  if(item.month===''||item.day===''||item.hour===''){
                     fla = true
                  }
              })
              if(fla){
                this.$message.warning('周期信息需补充完整！')
                return;
              }
              break;
      }
      this.$refs.contentConfigForm.validate(async valid => {
        if (valid) {
          // let form = deepClone(this.formData)
          // form.ruleCycleList = this.$refs.cycleMultipleRef.ruleCycleList
          // form.ruleItems.forEach(item => {
          //   if (item.ruleType) {
          //     item.ruleType = this.ruleTypeObj[item.ruleType.code]
          //   }
          // })
          let res = await saveOrUpdate(form)
          if (res) {
            this.$message.success('操作成功！')
            this.handleClose()
            this.$emit('done')
          }
        } else {
          this.$message.warning('请将信息补充完整！')
        }
      })
    },
  }
}
</script>
<style scoped lang="scss">
.form-ipt {
  width: 310px;
}
.details-div {
  font-size: 14px;
  padding-left: 40px;
  .details-div-title {
    display: flex;
    justify-content: space-between;
    span {
      padding-top: 8px;
    }
  }
}
.zw-container {
  height: 450px;
}
.page-footer-btn {
  margin: 20px 0;
  text-align: center;
}
// .app-container {
::v-deep .el-form-item {
  margin-bottom: 14px;
}
::v-deep .el-table__body-wrapper {
  .el-form-item {
    margin-bottom: 0;
  }
}
::v-deep .el-form-item__error {
  padding-top: 0;
}
.cycle_value {
  ::v-deep .el-input__inner {
    text-align: center;
  }
}
// }
</style>
