<template>
  <ele-modal
    :title="title"
    :visible.sync="visible"
    :close-on-click-modal="false"
    @close="handleClose"
    resizable
    maxable
    width="80%"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="130px"
      v-loading="loading"
      :disabled="type == 'detail'"
    >
      <header-title title="基本信息"></header-title>
      <el-row style="margin-bottom: 15px" gap="10">
        <el-col :span="8">
          <el-form-item label="放行类型" prop="checklistType">
            <DictSelection
              dictName="放行类型"
              clearable
              v-model="form.checklistType"
            >
            </DictSelection>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="放行模板编码">
            <el-input
              v-model="form.templateCode"
              placeholder="系统自动生成"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="放行模板名称" prop="templateName">
            <el-input
              v-model="form.templateName"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row style="margin-bottom: 15px" gap="10">
        <el-col :span="8">
          <el-form-item label="状态" prop="enable">
            <el-radio-group v-model="form.enable">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">停用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="备注">
            <el-input
              type="textarea"
              :rows="2"
              v-model="form.remark"
              placeholder="放行单业务说明"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <header-title title="生产放行规则">
        <el-button type="primary" icon="el-icon-plus" @click="addDetails(1)">
          添加规则指标
        </el-button>
      </header-title>

      <ele-pro-table
        ref="scTable"
        row-key="id"
        :columns="columns"
        :datasource="scCheckTypeDetails"
      >
        <template v-slot:businessType="{ row }">
          <el-select
            v-model="row.businessType"
            placeholder="请选择业务类型"
            @change="businessTypeChange(row)"
          >
            <el-option
              v-for="i in indicatorUseLevelList"
              :key="i.businessType"
              :label="i.businessName"
              :value="i.businessType"
            >
            </el-option>
          </el-select>
        </template>
        <template v-slot:indicator="{ row }">
          <el-select
            v-if="row.businessType !== -1"
            v-model="row.indicator"
            placeholder="请选择考核指标"
            :key="row.businessType"
            @change="indicatorChange(row)"
          >
            <el-option
              v-for="i in getIndicatorList(row.businessType)"
              :key="i.indicator"
              :label="i.indicatorName"
              :value="i.indicator"
            >
            </el-option>
          </el-select>
          <el-input
            v-else
            v-model="row.indicatorName"
            placeholder="请输入"
          ></el-input>
        </template>
        <template v-slot:indicatorName="{ row }">
          <el-select
            v-if="row.businessType !== -1"
            v-model="row.mainIndicatorId"
            placeholder="请选择指标名称"
            :key="row.indicator"
            @change="mainIndicatorIdChange(row)"
          >
            <el-option
              v-for="i in getMainIndicatorIdList(
                row.businessType,
                row.indicator
              )"
              :key="i.id"
              :label="i.name"
              :value="i.id"
            >
            </el-option>
          </el-select>
          <el-input
            v-else
            v-model="row.mainIndicatorName"
            placeholder="请输入"
          ></el-input>
        </template>
        <template v-slot:isAutoCheck="{ row }">
          <el-select
            v-model="row.isAutoCheck"
            placeholder="请选择"
            :disabled="row.businessType === -1"
          >
            <el-option label="自动" :value="1"> </el-option>
            <el-option label="手动" :value="0"> </el-option>
          </el-select>
        </template>
        <template v-slot:action="{ row }">
          <div>
            <el-link type="danger" @click="deleteRow(row)">删除</el-link>
          </div>
        </template>
      </ele-pro-table>

      <header-title title="质检放行规则">
        <el-button type="primary" icon="el-icon-plus" @click="addDetails(2)">
          添加规则指标
        </el-button>
      </header-title>

      <ele-pro-table
        ref="zjTable"
        row-key="id"
        :columns="columns"
        :datasource="zjCheckTypeDetails"
      >
        <template v-slot:businessType="{ row }">
          <el-select
            v-model="row.businessType"
            placeholder="请选择业务类型"
            @change="businessTypeChange(row)"
          >
            <el-option
              v-for="i in indicatorUseLevelList"
              :key="i.businessType"
              :label="i.businessName"
              :value="i.businessType"
            >
            </el-option>
          </el-select>
        </template>
        <template v-slot:indicator="{ row }">
          <el-select
            v-if="row.businessType !== -1"
            v-model="row.indicator"
            placeholder="请选择考核指标"
            :key="row.businessType"
            @change="indicatorChange(row)"
          >
            <el-option
              v-for="i in getIndicatorList(row.businessType)"
              :key="i.indicator"
              :label="i.indicatorName"
              :value="i.indicator"
            >
            </el-option>
          </el-select>
          <el-input
            v-else
            v-model="row.indicatorName"
            placeholder="请输入"
          ></el-input>
        </template>
        <template v-slot:indicatorName="{ row }">
          <el-select
            v-if="row.businessType !== -1"
            v-model="row.mainIndicatorId"
            placeholder="请选择指标名称"
            :key="row.indicator"
            @change="mainIndicatorIdChange(row)"
          >
            <el-option
              v-for="i in getMainIndicatorIdList(
                row.businessType,
                row.indicator
              )"
              :key="i.id"
              :label="i.name"
              :value="i.id"
            >
            </el-option>
          </el-select>
          <el-input
            v-else
            v-model="row.mainIndicatorName"
            placeholder="请输入"
          ></el-input>
        </template>
        <template v-slot:isAutoCheck="{ row }">
          <el-select v-model="row.isAutoCheck" placeholder="请选择">
            <el-option label="自动" :value="1"> </el-option>
            <el-option label="手动" :value="0"> </el-option>
          </el-select>
        </template>
        <template v-slot:action="{ row }">
          <div>
            <el-link type="danger" @click="deleteRow(row)">删除</el-link>
          </div>
        </template>
      </ele-pro-table>
    </el-form>

    <template v-slot:footer>
      <el-button
        v-if="type == 'edit'"
        type="primary"
        @click="submit('edit')"
        :loading="buttonLoading"
        >保 存</el-button
      >

      <el-button
        v-if="type == 'add' || type == 'clone'"
        type="primary"
        @click="submit('add')"
        :loading="buttonLoading"
        >提 交</el-button
      >

      <el-button @click="handleClose" style="margin-left: 20px"
        >取 消</el-button
      >
    </template>
  </ele-modal>
</template>

<script>
  import dictMixins from '@/mixins/dictMixins';
  import {
    checklisttemplateGetById,
    checktemplateSave,
    checklisttemplateUpdate
  } from '@/api/checklisttemplate/index';
  import { getIndicatorUseLevel } from '@/api/main/index';
  import { getByTypeAndIndicator } from '@/api/eom/index';

  export default {
    mixins: [dictMixins],
    data() {
      const formBaseData = {
        id: null,
        createUserName: '',
        details: [],
        enable: 1,
        remark: '',
        templateCode: '',
        templateName: '',
        checklistType: ''
      };

      return {
        visible: false,
        title: '新增放行单模版',
        formBaseData,
        form: JSON.parse(JSON.stringify(formBaseData)),
        rules: {
          checklistType: [
            { required: true, message: '请选择放行类型', trigger: 'blur' },
            { required: true, message: '请选择放行类型', trigger: 'change' }
          ],
          templateName: [
            { required: true, message: '请输入放行单名称', trigger: 'blur' },
            { required: true, message: '请输入放行单名称', trigger: 'change' }
          ],
          enable: [
            { required: true, message: '请选择状态', trigger: 'blur' },
            { required: true, message: '请选择状态', trigger: 'change' }
          ]
        },
        // 业务类型和考核指标
        indicatorUseLevelList: [],
        // 操作类型 add-新增 edit-编辑 clone-克隆
        type: 'add',
        loading: false,
        buttonLoading: false
      };
    },
    computed: {
      // 生产放行规则
      scCheckTypeDetails() {
        return this.form.details.filter((item) => item.checkType == 1);
      },
      // 质检放行规则
      zjCheckTypeDetails() {
        return this.form.details.filter((item) => item.checkType == 2);
      },
      columns() {
        return [
          {
            width: 55,
            type: 'index',
            columnKey: 'index',
            label: '序号',
            align: 'center'
          },
          {
            prop: 'businessType',
            label: '业务类型',
            slot: 'businessType',
            align: 'center',
            minWidth: 150,
            showOverflowTooltip: true
          },
          {
            prop: 'indicator',
            label: '考核指标',
            slot: 'indicator',
            align: 'center',
            minWidth: 150,
            showOverflowTooltip: true
          },
          {
            prop: 'indicatorName',
            label: '指标名称',
            slot: 'indicatorName',
            align: 'center',
            minWidth: 150,
            showOverflowTooltip: true
          },
          {
            prop: 'isAutoCheck',
            label: '结果输出类型',
            slot: 'isAutoCheck',
            align: 'center',
            minWidth: 150,
            showOverflowTooltip: true
          },
          {
            columnKey: 'action',
            label: '操作',
            width: 120,
            align: 'center',
            resizable: false,
            fixed: 'right',
            slot: 'action'
          }
        ];
      }
    },
    created() {
      this.getIndicatorUseLevel();
    },
    methods: {
      // 外部调用，打开弹窗
      open(type, data) {
        console.log('type, data', type, data);
        this.type = type;
        if (type == 'add') {
          this.title = '新增放行单模版';
        } else if (type == 'edit') {
          this.title = '编辑放行单模版';
          this.getDetails(data.id);
        } else if (type == 'detail') {
          this.title = '放行单模版详情';
          this.getDetails(data.id);
        } else {
          // 克隆
          this.title = '克隆放行单模版';
          this.getDetails(data.id);
        }
        this.visible = true;
      },
      async getDetails(id) {
        this.loading = true;
        try {
          const res = await checklisttemplateGetById(id);
          console.log('res', res);
          this.$util.assignObject(this.form, res);

          this.loading = false;
        } catch (error) {
          this.loading = false;
        }
      },
      // 关闭时清理表单
      handleClose() {
        this.visible = false;
        this.form = JSON.parse(JSON.stringify(this.formBaseData));
        this.$refs.formRef && this.$refs.formRef.resetFields();
      },
      // 提交
      submit(type) {
        console.log('this.form', this.form);
        console.log('this.form.details', this.form.details);
        this.$refs.formRef.validate(async (valid) => {
          if (valid) {
            if (this.form.details.length == 0) {
              return this.$message.warning('请至少添加一条放行规则!');
            }

            // 判断details中的 businessType、indicator、indicatorName 是否有空值
            for (let i = 0; i < this.form.details.length; i++) {
              const item = this.form.details[i];

              if (item.businessType === null) {
                return this.$message.warning(
                  '请填写完整放行规则，业务类型、考核指标、指标名称不能为空!'
                );
              }

              if (
                item.businessType !== -1 &&
                (item.indicator == null || item.mainIndicatorId == null)
              ) {
                return this.$message.warning(
                  '请填写完整放行规则，业务类型、考核指标、指标名称不能为空!'
                );
              }

              if (
                item.businessType == -1 &&
                (item.indicatorName == '' || item.mainIndicatorName == '')
              ) {
                return this.$message.warning(
                  '请填写完整放行规则，业务类型、考核指标、指标名称不能为空!'
                );
              }
            }
            this.buttonLoading = true;

            try {
              if (type == 'add' || type == 'clone') {
                this.form.createUserName = this.$store.state.user?.info.name;
                this.form.id = null;
                // 重置id
                this.form.details.forEach((item) => {
                  item.id = null;
                });
                await checktemplateSave(this.form);
              } else {
                // 过滤临时id
                this.form.details = this.form.details.map((item) => {
                  if (
                    typeof item.id === 'string' &&
                    item.id.startsWith('tem-')
                  ) {
                    return { ...item, id: null };
                  }
                  return item;
                });
                // 编辑
                await checklisttemplateUpdate(this.form);
              }
            } catch (error) {
              return (this.buttonLoading = false);
            }

            this.buttonLoading = false;

            this.$message.success('操作成功');
            // 触发父组件刷新
            this.$emit('reload');

            this.handleClose();
          }
        });
      },
      // 获取获取指标根节点列表
      async getIndicatorUseLevel() {
        const data = await getIndicatorUseLevel();
        // 添加其他选项
        data.push({
          businessName: '其他',
          businessType: -1,
          children: []
        });
        this.indicatorUseLevelList = data;
        console.log('this.getIndicatorUseLevel', this.indicatorUseLevelList);
      },

      // 添加规则指标 1-生产放行规则，2-质检放行规则
      addDetails(checkType = 1) {
        const maxSortNum = this.form.details.reduce((max, item) => {
          return item.sortNum > max ? item.sortNum : max;
        }, 0);

        const newSortNum = maxSortNum + 1;

        this.form.details.push({
          businessType: null,
          businessName: '',
          checkType: checkType,
          createUserName: this.$store.state.user?.info.name,
          indicator: null,
          indicatorName: '',
          isAutoCheck: 1,
          sortNum: newSortNum,
          mainIndicatorId: null,
          mainIndicatorName: '',
          templateId: null,
          // 临时id
          id: `tem-${new Date().getTime()}`
        });
      },
      // 业务类型 考核指标
      getIndicatorList(businessType) {
        const item = this.indicatorUseLevelList.find(
          (item) => item.businessType == businessType
        );
        return item ? item.children : [];
      },
      // 业务类型改变 重置指标和指标名称
      businessTypeChange(row) {
        const item = this.indicatorUseLevelList.find(
          (item) => item.businessType == row.businessType
        );
        row.businessName = item ? item.businessName : '';

        row.indicator = null;
        row.indicatorName = '';
        row.mainIndicatorId = null;
        row.mainIndicatorName = '';

        if (row.businessType === -1) {
          row.isAutoCheck = 0;
        } else {
          // row.isAutoCheck = 1;
        }
      },
      // 修改 考核指标
      indicatorChange(row) {
        const list = this.getIndicatorList(row.businessType);
        const indicatorItem = list?.find(
          (item) => item.indicator == row.indicator
        );

        row.indicatorName = indicatorItem?.indicatorName || '';
        row.mainIndicatorId = null;
        row.mainIndicatorName = '';
      },
      // 指标名称列表
      getMainIndicatorIdList(businessType, indicator) {
        // 排除其他
        if (businessType == -1) return;
        const indicatorList = this.getIndicatorList(businessType);
        const indicatorItem = indicatorList?.find(
          (item) => item.indicator == indicator
        );
        console.log('indicatorItem', indicatorItem);
        return indicatorItem?.children || [];
      },

      // 删除行
      deleteRow(row) {
        this.form.details = this.form.details.filter(
          (item) => item.id !== row.id
        );
      },
      // 选择指标名称
      mainIndicatorIdChange(row) {
        const list = this.getMainIndicatorIdList(
          row.businessType,
          row.indicator
        );
        const item = list.find((i) => i.id == row.mainIndicatorId);
        row.mainIndicatorName = item ? item.name : '';
      }
    }
  };
</script>

<style scoped lang="scss"></style>
