    <!--
 * @Author: zhp
 * @Date: 2023-02-14 15:02:26
 * @LastEditTime: 2023-07-19 16:17:25
 * @LastEditors: zhp
 * @Description: 
-->
<template>
  <el-drawer close-on-press-escape title="提示" :visible.sync="visible" size="50%" :before-close="handleClose()">
    <el-tabs @tab-click="handleClickTab" v-model="title" tab-position="left" style="margin-bottom: 30px;">
      <el-tab-pane label="项目概述" name="first">
        <el-form :model="dataForm" ref="dataForm" :rules="dataRule" @keyup.enter.native="dataFormSubmitHandle()"
          label-width="120px">
          <el-form-item prop="productId" :label="$t('basic.productName')">
            <el-select v-model="dataForm.productId" :placeholder="$t('basic.productName')" clearable>
              <el-option v-for="item in productList" :key="item.id" :label="item.productName" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="knowledgeBaseId" :label="$t('customerquality.knowledgeBase')">
            <el-select v-model="dataForm.knowledgeBaseId" :placeholder="$t('customerquality.knowledgeBase')" clearable>
              <el-option v-for="item in knowledgeBaseList" :key="item.id" :label="item.knowledgeBaseName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="customerId" :label="$t('customerquality.customerName')">
            <el-select v-model="dataForm.customerId" :placeholder="$t('customerquality.customerName')" clearable>
              <el-option v-for="item in customerList" :key="item.id" :label="item.customerName" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="qualityAcceptanceDate" :label="$t('customerquality.qualityAcceptanceDate')">
            <el-date-picker clearable v-model="dataForm.qualityAcceptanceDate" type="datetime"
              :placeholder="$t('customerquality.qualityAcceptanceDate')">
            </el-date-picker>
          </el-form-item>
          <el-form-item prop="deliveryRequiredDate" :label="$t('customerquality.deliveryRequiredDate')">
            <el-date-picker clearable v-model="dataForm.deliveryRequiredDate" type="datetime"
              :placeholder="$t('customerquality.deliveryRequiredDate')">
            </el-date-picker>
          </el-form-item>
          <el-form-item prop="confirmDeliveryDate" :label="$t('customerquality.confirmDeliveryDate')">
            <el-date-picker clearable v-model="dataForm.confirmDeliveryDate" type="datetime"
              :placeholder="$t('customerquality.confirmDeliveryDate')">
            </el-date-picker>
          </el-form-item>
          <el-form-item prop="first" :label="$t('customerquality.first')">
            <el-select clearable v-model="dataForm.first" :placeholder="$t('customerquality.first')">
              <el-option v-for="item in firstList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="previousVersionCode" :label="$t('customerquality.previousVersionCode')">
            <el-input clearable v-model="dataForm.previousVersionCode"
              :placeholder="$t('customerquality.previousVersionCode')">
            </el-input>
          </el-form-item>
          <el-form-item prop="author" label="Author/Owner">
            <el-input clearable v-model="dataForm.author" placeholder="Author/Owner">
            </el-input>
          </el-form-item>
          <el-form-item prop="releaser" label="releaser">
            <el-input clearable v-model="dataForm.releaser" placeholder="releaser">
            </el-input>
          </el-form-item>
          <el-form-item prop="confidentialityAgreement" :label="$t('customerquality.first')">
            <el-select clearable v-model="dataForm.confidentialityAgreement" :placeholder="$t('customerquality.first')">
              <el-option v-for="item in confidentialityAgreementList" :key="item.id" :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="nda" label="nda">
            <el-select clearable v-model="dataForm.nda" placeholder="nda">
              <el-option v-for="item in ndaList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="status" label="状态">
            <el-select clearable v-model="dataForm.status" placeholder="状态">
              <el-option v-for="item in statusList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="ppapGrade" :label="$t('customerquality.ppapGrade')">
            <el-select clearable v-model="dataForm.ppapGrade" :placeholder="$t('customerquality.ppapGrade')">
              <el-option v-for="item in ppapGradeList" :key="item.id" :label="item.dataDictionaryDetailName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="version" :label="$t('customerquality.version')">
            <el-input clearable v-model="dataForm.version" :placeholder="$t('customerquality.version')">
            </el-input>
          </el-form-item>
          <el-form-item prop="amendment" :label="$t('customerquality.amendment')">
            <el-input clearable v-model="dataForm.amendment" :placeholder="$t('customerquality.amendment')">
            </el-input>
          </el-form-item>
          <el-form-item prop="description" :label="$t('customerquality.description')">
            <el-input clearable v-model="dataForm.description" :placeholder="$t('customerquality.description')">
            </el-input>
          </el-form-item>
        </el-form>
        <span style="float: right;" class="dialog-footer">
          <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
          <el-button type="primary" @click="dataFormSubmit()"> {{ $t('save') }} </el-button>
        </span>
      </el-tab-pane>
      <el-tab-pane :disabled="tabDisable" label="要求清单" name="second">
        <el-tree :default-checked-keys="defaultData" :data="treeData" show-checkbox @check="handleCheckChange"
          node-key="id">
        </el-tree>
        <span style="float: right;" class="dialog-footer">
          <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
          <el-button type="primary" @click="projectListRequirementListDataFormSubmit()"> {{ $t('save')
          }} </el-button>
        </span>
      </el-tab-pane>
      <el-tab-pane :disabled="tabDisable" label="封面生成" name="three">
        <el-divider content-position="center">修订记录</el-divider>
        <SearchBar :formConfigs="reviseFormConfig" ref="ruleForm" @headBtnClick="buttonClick">
        </SearchBar>
        <base-table id="palletTable" :table-props="tableProps" :page="listQuery.page" ref="palletTable1"
          :limit="listQuery.limit" :table-data="tableData">
          <method-btn v-if="tableBtn.length" slot="handleBtn" :width="100" label="操作" :method-list="tableBtn"
            @clickBtn="handleClick" />
        </base-table>
        <pagination :limit.sync="listQuery.limit" :page.sync="listQuery.page" :total="listQuery.total"
          @pagination="getDataList" />
        <revise-add ref="reviseAddList" v-if="reviseAddShow" @refreshDataList="getDataList">
        </revise-add>
        <el-divider content-position="center">变更记录</el-divider>
        <SearchBar :formConfigs="changeFormConfig" ref="ruleForm" @headBtnClick="changeButtonClick">
        </SearchBar>
        <base-table id="palletTable" :table-props="changeTableProps" :page="changeListQuery.page" ref="palletTable1"
          :limit="changeListQuery.limit" :table-data="changeTableData">
          <method-btn v-if="changeTableBtn.length" slot="handleBtn" :width="100" label="操作"
            :method-list="changeTableBtn" @clickBtn="changeHandleClick" />
        </base-table>
        <pagination :limit.sync="changeListQuery.limit" :page.sync="changeListQuery.page" :total="changeListQuery.total"
          @pagination="changeGetDataList" />
        <change-add ref="changeAddList" v-if="changeAddShow" @refreshDataList="changeGetDataList">
        </change-add>
      </el-tab-pane>
    </el-tabs>
  </el-drawer>
</template>

<script>
import debounce from "lodash/debounce"
import basicAdd from "@/mixins/basic-add"
import reviseAdd from "./revise-add"
import changeAdd from "./change-add"
import i18n from "@/i18n"
import { timeFormatter } from '@/filters'
const tableProps = [
  {
    prop: "revision",
    label: 'revision',
  },
  {
    prop: "date",
    label: 'date',
    filter: timeFormatter
  },
  {
    prop: "item",
    label: 'Item/Section',
  },
  {
    prop: "essential",
    label: 'Essential Changes',
    // filter: timeFormatter
  },
];
const tableBtn = [
  {
    type: "edit",
    btnName: i18n.t('edit'),
  },
  {
    type: "delete",
    btnName: i18n.t('delete'),
  },
  // {
  //   type: "configuration",
  //   btnName: i18n.t('configuration'),
  // }
];
const changeTableProps = [
  {
    prop: "changeHistory",
    label: '	Change History of this PPAP record',
  },
  {
    prop: "date",
    label: 'date',
    filter: timeFormatter
  },
  {
    prop: "name",
    label: 'name',
  },
];
const changeTableBtn = [
  {
    type: "edit",
    btnName: i18n.t('edit'),
  },
  {
    type: "delete",
    btnName: i18n.t('delete'),
  },
  // {
  //   type: "configuration",
  //   btnName: i18n.t('configuration'),
  // }
];
export default {
  mixins: [basicAdd],
  components: {
    reviseAdd,
    changeAdd
  },
  data() {
    return {
      urlOptions: {
        getReviseDataListURL: '/customerquality/qmsCustomerQualityProjectListRevisionRecord/page',
        getChangeDataListURL: '/customerquality/qmsCustomerQualityProjectListChangeRecord/page',
        changeDeleteURL: '/customerquality/qmsCustomerQualityProjectListChangeRecord',
        reviseDeleteURL: '/customerquality/qmsCustomerQualityProjectListRevisionRecord',
        submitURL: "/customerquality/qmsCustomerQualityProjectList",
        infoURL: "/customerquality/qmsCustomerQualityProjectList//{id}",
        getDictDataDetail: '/mutual/qmsDataDictionaryDetail/page',
        getProductURL: '/basic/qmsProduct/page',
        getKnowledgeBaseURL: '/customerquality/qmsKnowledgeBase/page',
        getCustomerURL: '/basic/qmsCustomer/page',
        getRequirementListURL: '/customerquality/qmsCustomerQualityRequirementList/page',
        getProjectRequirementListURL: '/customerquality/qmsCustomerQualityProjectListRequirementList/page',
        projectListRequirementListSubmitURL: '/customerquality/qmsCustomerQualityProjectListRequirementList/savelist',
        projectListRequirementListEditURL: '/customerquality/qmsCustomerQualityProjectListRequirementList/updatelist',
      },
      tableBtn,
      reviseAddShow: false,
      changeAddShow: false,
      ndaList: [
        {
          id: '0',
          name: '错号',
        },
        {
          id: '1',
          name: '对号',
        }
      ],
      statusList: [
        {
          id: '0',
          name: '待审核',
        },
        {
          id: '1',
          name: '已完成',
        },
        {
          id: '2',
          name: '交付退回',
        },
        {
          id: '3',
          name: '审核拒绝',
        }
      ],
      reviseFormConfig: [
        {
          type: "button",
          btnName: i18n.t('search'),
          name: "search",
          color: "primary",
          // plain: true,
        },
        {
          type: "button",
          btnName: i18n.t('add'),
          name: "add",
          color: "success",
          plain: true
        }
      ],
      changeFormConfig: [
        {
          type: "button",
          btnName: i18n.t('search'),
          name: "search",
          color: "primary",
          // plain: true,
        },
        {
          type: "button",
          btnName: i18n.t('add'),
          name: "add",
          color: "success",
          plain: true
        }
      ],
      tableProps,
      tableData: [],
      changeTableProps,
      changeTableData: [],
      changeTableBtn,
      listQuery: {
        page: 1,
        limit:10
      },
      checkArr:[],
      customerQualityProjectListId:null,
      productList: [],
      title:'first',
      customerList: [],
      ppapGradeList:[],
      knowledgeBaseList: [],
      firstList: [
        {
          id: '0',
          name:'否',
        },
        {
          id: '1',
          name: '是',
        }
      ],
      defaultData:[],
      confidentialityAgreementList: [
        {
          id: '0',
          name: '否',
        },
        {
          id: '1',
          name: '是',
        }
      ],
      categoryList:[],
      typeList:[],
      visible: false,
      listQuery: {
        limit: 999,
        page: 1,
        total:0,
      },
      changeListQuery: {
        limit: 999,
        page: 1,
        total: 0,
      },
      treeData: [],
      tabDisable:true,
      dataForm: {
        nda: null,
        amendment: null,
        status:null,
        confidentialityAgreement:null,
        confirmDeliveryDate: null,
        customerId: null,
        deliveryRequiredDate: null,
        description: null,
        releaser: null,
        author:null,
        first: null,
        id: undefined,
        knowledgeBaseId: null,
        ppapGrade: null,
        previousVersionCode: null,
        productId: null,
        qualityAcceptanceDate: null,
        version: null,
      },
    };
  },
  computed: {
    dataRule() {
      return {
        productId: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "change",
          },
        ],
        knowledgeBaseId: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "change",
          },
        ],
        customerId: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "change",
          },
        ],
        qualityAcceptanceDate: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "change",
          },
        ],
        deliveryRequiredDate: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "change",
          },
        ],
        ppapGrade: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ]
      };
    },
  },
  mounted () {
    this.getDict()
    this.getSecondData()
  },
  methods: {
    changeGetDataList() {
      this.listQuery.customerQualityProjectListId = this.dataForm.id ? this.dataForm.id : this.customerQualityProjectListId
      this.dataListLoading = true;
      this.$http
        .get(this.urlOptions.getChangeDataListURL, {
          params: this.listQuery,
        })
        .then(({ data: res }) => {
          this.dataListLoading = false;
          if (res.code !== 0) {
            this.changeTableData = [];
            this.listQuery.total = 0;
            return this.$message.error(res.msg);
          }
          this.changeTableData = res.data.list;
          this.changeListQuery.total = res.data.total;
        })
        .catch(() => {
          this.dataListLoading = false;
        })
    },
     changeHandleClick(val) {
      if (val.type === "delete") {
        this.$confirm(`确定对[名称=${val.data.customerTypeName}]进行删除操作?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.$http.delete(this.urlOptions.reviseDeleteURL, { data: [val.data.id] }).then(({ data }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.getDataList()
                  },
                });
              } else {
                this.$message.error(data.msg);
              }
            });
          })
          .catch(() => { });
      } else if (val.type === 'edit') {
        let obj = {
          customerQualityProjectListId: this.dataForm.id ? this.dataForm.id : this.customerQualityProjectListId,
          id: val.data.id
        }
        this.$nextTick(() => {
          this.$refs.reviseAddList.init(obj)
        })
      }
    },
     changeButtonClick(val) {
      console.log(this.dataForm.id)
      console.log(val);
      switch (val.btnName) {
        case "search":
          this.listQuery.page = 1
          this.getDataList()
          break;
        case "add":
          this.changeAddShow = true
          let obj = {
            customerQualityProjectListId: this.dataForm.id ? this.dataForm.id : this.customerQualityProjectListId
          }
          this.$nextTick(() => {
            this.$refs.changeAddList.init(obj)
          })
          break;
        default:
      }
    },
    getDataList() {
      this.dataListLoading = true
      this.listQuery.customerQualityProjectListId = this.dataForm.id ? this.dataForm.id : this.customerQualityProjectListId
      this.$http
        .get(this.urlOptions.getReviseDataListURL, {
          params: this.listQuery,
        })
        .then(({ data: res }) => {
          this.dataListLoading = false;
          if (res.code !== 0) {
            this.tableData = [];
            this.listQuery.total = 0;
            return this.$message.error(res.msg);
          }
          this.tableData = res.data.list;
          this.listQuery.total = res.data.total;
        })
        .catch(() => {
          this.dataListLoading = false;
        })
    },
    handleClick(val) {
      if (val.type === "delete") {
        this.$confirm(`确定对[revision为${val.data.revision}]进行删除操作?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.$http.delete(this.urlOptions.changeDeleteURL, { data: [val.data.id] }).then(({ data }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.getDataList()
                  },
                });
              } else {
                this.$message.error(data.msg);
              }
            });
          })
          .catch(() => { });
      } else if (val.type === 'edit') {
        let obj = {
          customerQualityProjectListId: this.dataForm.id ? this.dataForm.id : this.customerQualityProjectListId,
          id:val.data.id
        }
        this.$nextTick(() => {
          this.$refs.reviseAddList.init(obj)
        })
      }
    },
    buttonClick(val) {
      console.log(this.dataForm.id)
      console.log(val);
      switch (val.btnName) {
        case "search":
          // this.listQuery.paramCode = val.paramCode;
          // console.log(i18n);
          this.listQuery.page = 1
          this.getDataList()
          break;
        case "add":
          this.reviseAddShow = true
          let obj = {
            customerQualityProjectListId: this.dataForm.id ? this.dataForm.id : this.customerQualityProjectListId
          }
          this.$nextTick(() => {
            this.$refs.reviseAddList.init(obj)
          })
          break;
        default:
      }
    },
    handleClickTab(val) {
      console.log(val);
      if (val.name === 'second') {
        this.$http
          .get(this.urlOptions.getProjectRequirementListURL, {
            params: {
              limit: 999,
              page: 1,
              projectListId: this.dataForm.id ? this.dataForm.id : this.customerQualityProjectListId
            }
          })
          .then(({ data: res }) => {
            // this.dataListLoading = false;
            if (res.code === 0) {
              let arr = []
              console.log(res.data.list)
              res.data.list.forEach((item) => {
                arr.push(item.customerQualityRequirementListId)
              })
              this.defaultData = arr 
            }
          })
      } else if (val.name === 'third') {
        this.changeGetDataList()
        this.getDataList()
      }
    },
    init(id) {
      this.dataForm.id = id || ""
      // this.dataForm.dictTypeId = dictTypeId || "";
      this.visible = true;
      this.$nextTick(() => {
        // console.log(this.$refs.dataForm)
        this.$refs["dataForm"].resetFields()
        if (this.dataForm.id) {
          this.getInfo()
        } else {
          // this.getCode()
        }
      });
    },
    // 获取信息
    handleClose() {
      this.$emit("refreshDataList")
      // console.log(this.$refs.dataForm)
      // this.$refs.dataForm.resetFields()
    },
    getInfo() {
      this.$http
        .get(`/customerquality/qmsCustomerQualityProjectList/${this.dataForm.id}`)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          this.dataForm = {
            ...this.dataForm,
            ...res.data,
          }
          this.customerQualityProjectListId = res.data.id
          this.tabDisable = false
        })
        .catch(() => {})
    },
    getSecondData() {
      this.$http
        .get(this.urlOptions.getRequirementListURL, {
          params: {
            limit: 999,
            page: 1,
          }
        })
        .then(({ data: res }) => {
          // this.dataListLoading = false;
          if (res.code === 0) {
            this.treeData = res.data.list.map((item) => {
              return {
                label: item.requirementListName,
                id:item.id
              }
            })
            console.log(this.treeData);
          }
        })
    },
    getDict() {
      this.$http
        .get(this.urlOptions.getDictDataDetail, {
          params: {
            limit: 999,
            page: 1,
            dataDictionaryId:'1681202200846499841',
          }
        })
        .then(({ data: res }) => {
          // this.dataListLoading = false;
          if (res.code === 0) {
            this.ppapGradeList = res.data.list 
          }
        })
      this.$http
        .get(this.urlOptions.getProductURL, {
          params: {
            limit: 999,
            page: 1,
          }
        })
        .then(({ data: res }) => {
          // this.dataListLoading = false;
          if (res.code === 0) {
            this.productList = res.data.list
          }
        })
      this.$http
        .get(this.urlOptions.getKnowledgeBaseURL, {
          params: {
            limit: 999,
            page: 1,
          }
        })
        .then(({ data: res }) => {
          // this.dataListLoading = false;
          if (res.code === 0) {
            this.knowledgeBaseList = res.data.list
          }
        })
      this.$http
        .get(this.urlOptions.getCustomerURL, {
          params: {
            limit: 999,
            page: 1,
          }
        })
        .then(({ data: res }) => {
          // this.dataListLoading = false;
          if (res.code === 0) {
            this.customerList = res.data.list
          }
        })
    },
    handleCheckChange(data, v) {
      this.checkArr = v.checkedKeys.map((item) => {
        return {
          customerQualityProjectListId: this.dataForm.id ? this.dataForm.id : this.customerQualityProjectListId,
          customerQualityRequirementListId:item
        }
      })
      console.log(this.checkArr)
    },
    // handleNodeClick(data) {
    //   console.log(data)
    // },
    projectListRequirementListDataFormSubmit() {
      if (this.defaultData.length !== 0) {

        let customerQualityProjectListId = this.dataForm.id ? this.dataForm.id : this.customerQualityProjectListId
          let list= this.checkArr
        this.$http.put('/customerquality/qmsCustomerQualityProjectListRequirementList/updatelist?id='+customerQualityProjectListId,list )
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg);
              }
              this.$message({
                message: this.$t("prompt.success"),
                type: "success",
                duration: 500,
                onClose: () => {
                  // this.title = 'second'
                  // this.tabDisable = false
                  // this.customerQualityProjectListId = res.data
                },
              })
            })
        } else {
          this.$http.post(this.urlOptions.projectListRequirementListSubmitURL, this.checkArr)
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg);
              }
              this.$message({
                message: this.$t("prompt.success"),
                type: "success",
                duration: 500,
                onClose: () => {
                  // this.title = 'second'
                  // this.tabDisable = false
                  // this.customerQualityProjectListId = res.data
                },
              })
            })
        }
    },
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (!valid) {
          return false;
        }
        this.$http[!this.dataForm.id ? "post" : "put"](this.urlOptions.submitURL, this.dataForm)
          .then(({ data: res }) => {
            if (res.code !== 0) {
              return this.$message.error(res.msg);
            }
            this.$message({
              message: this.$t("prompt.success"),
              type: "success",
              duration: 500,
              onClose: () => {
                this.tabDisable = false
                this.customerQualityProjectListId = res.data
              },
            });
          })
          .catch(() => { });
      });
    },
    // 表单提交
    dataFormSubmitHandle: debounce(
      function () {
        this.$refs["dataForm"].validate((valid) => {
          if (!valid) {
            return false;
          }
          this.$http[!this.dataForm.id ? "post" : "put"](this.urlOptions.submitURL, this.dataForm)
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg);
              }
              this.$message({
                message: this.$t("prompt.success"),
                type: "success",
                duration: 500,
                onClose: () => {
                  console.log(1111);
                  this.visible = false;
                  this.$emit("successSubmit");
                },
              });
            })
            .catch(() => {});
        });
      },
      1000,
      { leading: true, trailing: false }
    ),
  },
};
</script>
