<template>
  <div>
    <el-dialog title="添加质控信息" :visible.sync="data.bSwitch" :close-on-click-modal="false" width="900px" top="7vh">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm"
        label-suffix=":">
        <el-row :gutter="0">
          <el-col :span="20">
            <el-form-item label="质控规则" prop="rule_id">
              <el-cascader :options="zkInfoArray"  v-model="ruleForm.ruleArray" placeholder="请选择质控规则" filterable clearable></el-cascader>
              <i class="el-icon-circle-plus-outline" style="font-size: 28px;margin-left: 10px;" @click="addRule"></i>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="0">
          <el-col :span="8">
            <el-form-item label="病案号">
              <el-input v-model="ruleForm.MED_REC_ID" disabled placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="床位号" >
              <el-input v-model="ruleForm.CWH" disabled placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="住院次数">
              <el-input v-model="ruleForm.AAA29" disabled placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="错误扣分" prop="down" >
              <el-input v-model="ruleForm.down" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="错误等级">
              <el-select v-model="ruleForm.level" disabled>
                <el-option v-for="(item,index) of addRuleOptions.levelArray" :key="index" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="错误分类" >
              <el-select v-model="ruleForm.type" disabled>
                <el-option v-for="(item,index) of addRuleOptions.typeArray" :key="index" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="接收端" prop="cate">
              <el-select v-model="ruleForm.cate" filterable clearable placeholder="请选择" style="width: 100%">
                <el-option v-for="item of receiving" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="接收科室" prop="JSKS">
              <el-select v-model="ruleForm.JSKS" filterable clearable multiple :filter-method="filterDeportments"
                         placeholder="请选择" style="width: 100%">
                <el-option v-for="(item,index) of deportments" :key="index" :label="item.name" :value="item.dep_id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="接收人" prop="JSR">
              <el-select v-model="ruleForm.JSR" filterable clearable multiple :filter-method="filterRecipient"
                placeholder="请选择" style="width: 100%">
                <el-option v-for="item of recipient" :key="item.id" :label="`${item.name} ${item.base_code}`"
                  :value="item.name" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="整改期限">
              <el-input-number v-model="ruleForm.correction_date" controls-position="right" :min="0" :max="100" placeholder="请输入"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="0">
          <el-col :span="24">
            <el-form-item label="整改说明" prop="basis">
              <el-input type="textarea" v-model="ruleForm.basis" placeholder="请填写整改说明"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="loading" @click="onSubmit">发送整改通知</el-button>
      </span>
    </el-dialog>
    <el-dialog title="添加质控规则" center :visible.sync="addRuleDialog" width="460px">
      <el-form :inline="true" :rules="zkRules" >
        <el-form-item label="质控类型" prop="zk_type">
          <el-radio v-model="addRuleForm.zk_type"  label="1">首页质控</el-radio>
          <el-radio v-model="addRuleForm.zk_type"  label="2">病历质控</el-radio>
        </el-form-item>
        <el-form-item label="质控名称" prop="field">
          <el-input v-model="addRuleForm.field" placeholder="请输入质控名称" style="width: 300px;"></el-input>
        </el-form-item>
        <el-form-item label="错误扣分" prop="down">
          <el-input  v-model.number="addRuleForm.down"  placeholder="请输入 0.5 到 100 之间的数字" style="width: 300px;line-height: 0px;" >
          </el-input>
          <span style="font-size: 12px;display: flex;line-height: 15px;padding-top: 5px;">请输入0.5-100之间的数字,1位小数</span>

        </el-form-item>
        <el-form-item label="错误级别" prop="level" >
          <el-select v-model="addRuleForm.level" placeholder="请选择错误级别" style="width: 300px;" >
            <el-option v-for="(item,index) in addRuleOptions.levelArray" :key="index" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="缺陷分类" prop="type" v-if="addRuleForm.zk_type == 1">
          <el-select v-model="addRuleForm.type" placeholder="请选择缺陷分类" style="width: 300px;">
            <el-option v-for="(item,index) in addRuleOptions.typeArray" :key="index" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="缺陷类型" prop="error_type" v-if="addRuleForm.zk_type == 1">
          <el-select v-model="addRuleForm.error_type" placeholder="请选择缺陷类型" style="width: 300px;" >
            <el-option v-for="(item,index) in addRuleOptions.errorTypeArray" :key="index" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="缺陷类别" prop="category" v-if="addRuleForm.zk_type == 1">
          <el-select v-model="addRuleForm.category" placeholder="请选择缺陷类别" style="width: 300px;">
            <el-option v-for="(item,index) in addRuleOptions.categoryArray" :key="index" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="质控描述" prop="desc" style="margin-left: 10px;">
          <el-input type="textarea" v-model="addRuleForm.desc" placeholder="请填写质控描述" style="width: 300px;"></el-input>
        </el-form-item>
      </el-form>
      <el-footer style="display: flex; justify-content: center; align-items: center; padding: 20px 0;">
        <el-button @click="addRule">取消</el-button>
        <el-button type="primary" @click="addRuleSubmit">提交</el-button>
      </el-footer>
    </el-dialog>
  </div>
</template>

<script>
import { getRuleData, getBlInfo, addCaseQuality, getStaffListData, getCaseCate, getSelectValue } from '@/api/qc';

export default {
  props: {
    data: {
      type: Object,
      default() {
        return {
          bSwitch: false,
          text: '',
          blbh: '',
        };
      },
    },
    AAA28: {
      type: String,
      default() {
        return false;
      },
    },
    MED_REC_ID: {
      type: [String, Number], // 根据实际类型定义
      required: true, // 是否必传
    },
    CWH: {
      type: [String, Number], // 根据实际类型定义
      required: true,
    },
    AAA29: {
      type: [String, Number], // 根据实际类型定义
      required: true,
    },
    JSKS: {
      type: [String, Number], // 根据实际类型定义
      required: true,
    }
  },
  data() {
    return {
      //添加质控
      zkTypeArray: [
        { label: '首页质控', value: 1, },
        { label: '病历质控', value: 2, },
      ],
      addRuleOptions:{
        levelArray:[
          {'id':0,'name':'强制'},
          {'id':1,'name':'建议'},
        ],
        typeArray:[
          {'id':1,'name':'患者基本信息'},
          {'id':2,'name':'诊疗信息'},
          {'id':3,'name':'费用信息'},
        ],
        errorTypeArray:[
          {'id':1,'name':'逻辑性'},
          {'id':2,'name':'规范性'},
          {'id':3,'name':'编码'},
        ],
        categoryArray:[
          {'id':1,'name':'A类'},
          {'id':2,'name':'B类'},
          {'id':3,'name':'C类'},
          {'id':4,'name':'D类'},
        ],
      },
      zkRules:{
        zk_type:[{ required: true, message: '请选择质控类型',trigger:'xx'},],
        field: [{ required: true, message: '请填写质控名称',trigger:'xx'}],
        down: [
         // { required: true, message: '年龄不能为空'},
          {required: true, message: '扣分需在 0.5 到 100 之间的数字',trigger:'xx' }
        ],
        level: [{ required: true, message: '请选择缺陷类型', trigger: 'xx' }],
        type: [{ required: true, message: '请选择缺陷分类', trigger: 'xx' }],
        error_type: [{ required: true, message: '请选择缺陷类型', trigger: 'xx' }],
        category: [{ required: true, message: '请选择缺陷类别', trigger: 'xx' }],
      },
      zkInfoArray:[],//
      addRuleDialog:false,
      addRuleForm:{zk_type:'1'},
      errorTypeArray:[
        {'id':1,'name':'强制'},
        {'id':2,'name':'建议'},
      ],
      //
      loading: false,
      selectData: {
        rule: [],
        category: [],
        title: [],
        type: [],
        level: [],
        zgjb: [],
      },
      deportments: [],
      recipient: [],
      caseCates: [],
      receiving: [],
      categoryOptions: [],
      ruleForm: {
        AAA28: '',
        ZYH: '',
        ZKR: [],
        ZKKS: '',
        JSR: [],
        JSKS: [this.JSKS],
        ZGJB: '',
        category: '',
        title: '',
        rule_id: '',
        type: '',
        notice: '',
        basis: '',
        level: '',
        ZGQX: undefined,
        score: undefined,
        cate: '',
        MED_REC_ID: this.MED_REC_ID,
        AAA29: this.AAA29,
        CWH: this.CWH,
      },
      rules: {
        AAA28: [{ required: true, message: '请输入', trigger: 'blur' }],
        ZKR: [{ required: true, message: '请输入', trigger: 'blur' }],
        ZKKS: [{ required: true, message: '请输入', trigger: 'blur' }],

        JSR: [{ required: true, message: '请输入', trigger: 'blur' }],
        JSKS: [{ required: true, message: '请输入', trigger: 'blur' }],
        ZGJB: [{ required: true, message: '请选择', trigger: 'blur' }],
        cate: [{ required: true, message: '请选择', trigger: 'blur' }],
        category: [{ required: true, message: '请选择', trigger: 'change' }],
        title: [{ required: true, message: '请选择', trigger: 'change' }],
        notice: [{ required: true, message: '请输入', trigger: 'blur' }],
        basis: [{ required: true, message: '请输入', trigger: 'blur' }],
        score: [{ required: true, message: '请输入', trigger: 'blur' }],
        level: [{ required: true, message: '请选择', trigger: 'blur' }],
        MED_REC_ID: [{ required: true, message: '请输入', trigger: 'blur' }],
        AAA29: [{ required: true, message: '请输入', trigger: 'blur' }],
        CWH: [{ required: true, message: '请输入', trigger: 'blur' }],
      },
    };
  },
  watch: {
    // Watch for changes in props and update ruleForm
    MED_REC_ID(newVal) {
      this.ruleForm.MED_REC_ID = newVal;
    },
    CWH(newVal) {
      this.ruleForm.CWH = newVal;
    },
    AAA29(newVal) {
      this.ruleForm.AAA29 = newVal;
    },
    // JSKS(newVal) {
    //   this.ruleForm.JSKS = newVal;
    //   this.setDefaultValue(newVal);
    // }
  },
  mounted() {
    this.getRuleData();
    // this.getBlInfo()
    this.getStaff();
    this.getDeportmentList();
    this.getCaseCateList();
    this.receivingEnd();
    this.zkSelectValue();
    this.$set(this.ruleForm, 'basis', this.data.text);
    this.$set(this.ruleForm, 'ZYH', this.AAA28);
    this.getStoredRealname(); // 获取当前登录人
    this.getZkInfo();
  },
  methods: {
    success(msg) {
      this.$message({
        message: msg,
        type: 'success',
      });
    },
    //获取人工质控规则
    getZkInfo(){
      this.$axios.post('/artificial/department/getZkInfo', {}).then(res => {
        this.zkInfoArray = res.data;
      })
    },
    //添加质控弹窗状态
    addRule(){
      this.addRuleDialog = !this.addRuleDialog;
    },
    //添加质控规则提交
    addRuleSubmit(){
      let params = this.addRuleForm;
      this.$axios.post('/artificial/department/addRule', params).then(res => {
        if (res.code == 200){
          this.getZkInfo();
          this.addRule();
          this.success(res.msg);
        }
      })
    },
    // 质控分类
    querySearchCategory(queryString, cb) {
      var categorys = this.selectData.category;
      var results = queryString ? categorys.filter(this.createFilterCategory(queryString)) : categorys;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilterCategory(queryString) {
      return restaurant => {
        return restaurant.toLowerCase().indexOf(queryString.toLowerCase()) === 0;
      };
    },
    handleSelectCategory(item) {
      this.$set(this.ruleForm, 'category', item);
    },
    // 质控项目
    querySearchTitle(queryString, cb) {
      var titles = this.selectData.title;
      var results = queryString ? titles.filter(this.createFilterTitle(queryString)) : titles;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilterTitle(queryString) {
      return restaurant => {
        return restaurant.toLowerCase().indexOf(queryString.toLowerCase()) === 0;
      };
    },
    handleSelectTitle(item) {
      this.$set(this.ruleForm, 'title', item);
    },
    // 质控类型
    querySearchType(queryString, cb) {
      var types = this.selectData.type;
      var results = queryString ? types.filter(this.createFilterType(queryString)) : types;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilterType(queryString) {
      return restaurant => {
        return restaurant.toLowerCase().indexOf(queryString.toLowerCase()) === 0;
      };
    },
    handleSelectType(item) {
      this.$set(this.ruleForm, 'type', item);
    },
    // 获取规则数据
    getRuleData() {
      getRuleData().then(res => {
        this.$set(this, 'selectData', res.data);
      });
    },

    // 质控模板变化
    handleRuleIdChange(val) {
      if (val) {
        const item = this.zkInfoArray.filter(item => item.id)[0];
        const { category, error_type, notice, down, type, title ,level} = item;
        this.$set(this.ruleForm, 'category', category);
        this.$set(this.ruleForm, 'error_type', error_type);
        this.$set(this.ruleForm, 'notice', notice);
        this.$set(this.ruleForm, 'down', item['down']);
        this.$set(this.ruleForm, 'type', item['type']);
        this.$set(this.ruleForm, 'title', title);
        this.$set(this.ruleForm, 'level', level);
      }
    },
    // 部门
    getDeportmentList() {
      this.$axios
        .get('/user/depDropDown')
        .then(res => {
          this.deportments = res.data;
        })
        .catch(error => {
          console.log(error);
        });
    },

    filterDeportments(val) {
      if (val) {
        // 过滤逻辑，根据输入的值模糊匹配姓名和工号
        this.deportments = this.deportments.filter(item => {
          return item.name.includes(val) || item.id.includes(val);
        });
      } else {
        // 若输入为空，显示所有选项
        this.getDeportmentList();
      }
    },
    // 类别
    getCaseCateList() {
      this.$axios
        .post('/bl_zk/getCaseCate')
        .then(res => {
          const { data } = res;

          if (data.length) {
            this.caseCates = data;
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 提交
    onSubmit() {
      let params = {};
      params['MED_REC_ID'] = this.ruleForm.MED_REC_ID;
      params['ruleArray'] = this.ruleForm.ruleArray;
      params['cate'] = this.ruleForm.cate;
      params['JSKS'] = this.ruleForm.JSKS;
      params['JSR'] = this.ruleForm.JSR;
      params['basis'] = this.ruleForm.basis;
      this.$axios.post('artificial/department/addQualityControlInfo',params).then(res=>{
        if (res.code == 200){
          this.$emit('close');
          this.success(res.msg);
        }
      })
      return;
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          const { ZYH, ZKR, ZKKS, JSR, JSKS, ZGJB, category, title, rule_id, type, notice, basis, level, ZGQX, score, cate, MED_REC_ID, AAA29, CWH } = this.ruleForm;

          let JSRValue;
          if (Array.isArray(JSR)) {
            if (JSR.length === 1) {
              JSRValue = JSR[0];
            } else if (JSR.length > 1) {
              JSRValue = `[${JSR.join('、')}]`;
            } else {
              JSRValue = '';
            }
          } else {
            JSRValue = JSR;
          }

          let JSKSValue;
          if (Array.isArray(JSKS)) {
            JSKSValue = `[${JSKS.join('、')}]`;
          } else {
            JSKSValue = JSKS;
          }

          let ZKRValue;
          if (Array.isArray(ZKR)) {
            if (ZKR.length === 1) {
              ZKRValue = ZKR[0];
            } else if (ZKR.length > 1) {
              ZKRValue = `[${ZKR.join('、')}]`;
            } else {
              ZKRValue = '';
            }
          } else {
            ZKRValue = ZKR;
          }

          let ZKmlTitele;
          if (Array.isArray(title)) {
            if (title.length === 1) {
              ZKmlTitele = title[0];
            } else if (title.length > 1) {
              ZKmlTitele = `[${title.join('、')}]`;
            } else {
              ZKmlTitele = '';
            }
          } else {
            ZKmlTitele = title;
          }

          const params = {
            ZYH,
            ZKR: ZKRValue,
            ZKKS,
            JSR: JSRValue,
            JSKS: JSKSValue,
            ZGJB,
            category,
            title: ZKmlTitele,
            rule_id,
            type,
            notice,
            basis,
            level,
            ZGQX,
            score,
            cate,
            MED_REC_ID,
            AAA29,
            CWH,
          };


          this.loading = true;
          addCaseQuality(params)
            .then(res => {
              const { m } = res;
              this.$message.success(m || '成功');
              this.data.bSwitch = false;
              this.$emit('refresh');
            })
            .finally(res => {
              this.loading = false;
            });
        } else {
          return false;
        }
      });
    },
    // 获取存储的 realname
    getStoredRealname() {
      const storedRealname = localStorage.getItem('realname');

      if (storedRealname) {
        // 如果 realname 是字符串，转换为数组
        this.realname = storedRealname.split(',');
        // 设置默认值
        this.ruleForm.ZKR = this.realname;
      }
    },
    // 接收人
    getStaff() {
      getStaffListData().then(res => {
        const { data } = res;
        if (data.length) {
          data.forEach(ele => {
            this.recipient.push({
              id: ele.code,
              name: ele.name,
              base_code: ele.base_code,
            });
          });
        }
      });
    },
    filterRecipient(val) {
      if (val) {
        // 过滤逻辑，根据输入的值模糊匹配姓名和工号
        this.recipient = this.recipient.filter(item => {
          return item.name.includes(val) || item.id.includes(val);
        });
      } else {
        // 若输入为空，显示所有选项
        this.getStaff();
      }
    },
    // 接收端
    receivingEnd() {
      getCaseCate().then(res => {
        const { data } = res;
        if (data.length) {
          data.forEach(ele => {
            this.receiving.push({
              id: ele.id,
              name: ele.name,
            });
          });
        }
      });
    },
    // 质控目录
    zkSelectValue() {
      getSelectValue()
        .then(res => {
          // 将接口返回的数据转换为 el-cascader 所需的格式
          this.categoryOptions = this.transformData(res.data);
        })
        .catch(error => {
          console.error('获取选择值时出现错误:', error);
        });
    },
    // 转换数据格式
    transformData(data) {
      return data.map(item => ({
        id: item.id,
        label: item.field_name, // el-cascader 显示的字段
        children: item.child ? this.transformData(item.child) : null, // 递归处理子节点
      }));
    },

    // 处理选中的值
    handleCategoryChange(value) {
      // 根据选中的值执行逻辑
      if (value.length > 0) {
        const selectedIds = value; // 选中的 ID 数组
        const selectedNames = this.getSelectedNames(value); // 选中的名称数组
      }
    },
    // 获取选中的名称
    getSelectedNames(selectedIds) {
      let options = this.categoryOptions;
      const names = [];
      selectedIds.forEach(id => {
        const item = options.find(opt => opt.id === id);
        if (item) {
          names.push(item.label);
          if (item.children) options = item.children;
        }
      });
      return names;
    },
    customFilterMethod(node, keyword) {
      if (node.label.toLowerCase().includes(keyword.toLowerCase())) {
        return true;
      }

      // 递归检查子节点
      if (node.children && node.children.length > 0) {
        return node.children.some(child => this.customFilterMethod(child, keyword));
      }
      return false;
    },
    handleCategoryChange(value) {
      console.log('选中的值:', value);
    },
  },
};
</script>

<style lang="scss" scoped>
//::v-deep .el-form-item__content{line-height: 0px;}
.demo-ruleForm {
  width: 95%;
}

::v-deep .el-dialog__header {
  background-color: hsl(205.32deg 43.43% 49.22%);
}

::v-deep .el-dialog__title {
  color: #fff;
}

::v-deep .el-dialog__title {
  color: #fff;
}

::v-deep .el-dialog__close {
  color: #fff;
  border: 1px solid #fff;
  border-radius: 20px;
}

::v-deep .el-select .el-input__inner {
  overflow: hidden;
  white-space: nowrap;
}

::v-deep .el-select .el-select__tags {
  display: flex;
  flex-wrap: nowrap;
  overflow-x: auto;
  max-width: 100%;
}

::v-deep .el-select .el-select__tags::-webkit-scrollbar {
  display: none;
}

::v-deep .el-select .el-select__tags {
  -ms-overflow-style: none;
  scrollbar-width: none;
}

::v-deep .el-select .el-tag {
  margin-right: 4px;
  white-space: nowrap;
}
</style>
